Would that work for you?
if type( ((Mytable or {})[MyfirstLvl] or {}).Mysecondlvl ) == "table"
Question
I'm just starting to write Lua code for World of Warcraft. I frequently need to check to see if a global variable nested in a table has been defined by another author's Lua code.
Example:
Mytable[MyfirstLvl].Mysecondlvl.fred
where the variable MyfirstLvl1
has spaces in it
At present I'm using:
if (type(Mytable) == 'table') and (type(Mytable[MyfirstLvl]) == 'table') and (type(Mytable[MyfirstLvl].Mysecondlvl) == 'table') then
--some code using Mytable[MyfirstLvl].Mysecondlvl.fred
end
I'd like an easier way to do this. I thought of writing a function that uses _G
, but can't find any examples of parsing dynamic variable names that have '['
and ']'
in them.
Is there an easy way to tell if a value nested several levels down in a table has been defined or can someone help with creating a custom function to do this?
Here is what I came up with:
function newType(reference)
if type(reference) ~= 'string' then
print('...argument to Type must be a string')
return
end
local t = {string.split('].[', reference)}
local tt = {}
for k, v in ipairs(t) do
if string.len(v) ~= 0 then
local valueToInsert = v
if (string.sub(v, 1, 1) == '"') or (string.sub(v, 1, 1) == "'") then
valueToInsert = string.sub(v, 2, -2)
elseif tonumber(v) then
valueToInsert = tonumber(v)
end
table.insert(tt, valueToInsert)
end
end
local myReference = _G
local myType
for i, curArg in ipairs(tt) do
if type(myReference) ~= 'table' then
return 'nil'
end
if type(myReference[curArg]) ~= 'nil' then
myReference = myReference[curArg]
myType = type(myReference)
else
return 'nil'
end
end
return myType
end
SavedDB = {}
SavedDB.profiles = {}
SavedDB.profiles.Character = {}
SavedDB.profiles.Character.name = 'fireymerlin'
print(newType('SavedDB.profiles["Character"].name')
All of your comments helped me think this through. Thank you. If you see a better way to accomplish this (I hope the example at the bottom helps), please let me know. I was trying to make a function that I could pass one string to, but couldn't get the pattern matching to work when the string included ["Character"].
Solution
Would that work for you?
if type( ((Mytable or {})[MyfirstLvl] or {}).Mysecondlvl ) == "table"