Trying to use a table as a lookup for user generated data passed in externally.
tab = { ['on'] = function(x) x=x+1 return x end,
['off'] = function(x) x=x+2 return x end,
['high']= function(x) x=x+3 return x end,
['low'] = function(x) x=x+4 return x end
}
do
local var=0
local userData='on'
var = tab[userData](var)
print(var)
if var>0 then
--do something here
else
end
end
If the value exists in the table (userData='on') the program works as expected and prints
$lua main.lua
1
If the value does not exist in the table (userData='fluff') program fails
$lua main.lua
lua: main.lua:11: attempt to call a nil value (field '?')
stack traceback:
main.lua:11: in main chunk
[C]: in ?
How can I use a table like this if the keys do not exist?
you can use metatable for keys not exists. for example:
local tab = {}
setmetatable(tab, {__index = function()
return function(x)
return x + 1
end
end})
print(tab['on'](1))
the print result is: 2