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?
tab[userData]returns non-nil before attempting to make a function call with the result.