LUA table with function arguments and passing nil

Viewed 136

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?

2 Answers

The best solution is to not have the user enter invalid values in the first place.

If you cannot be sure userData is a key in tab you should check it befor using it to index tab

if not tab[userData] then
  print("invalid userdata")
  return
end

If you need tab[userData] to default to a function you can do something like this

tab[userData] = tab[userData] or function () print("I'm your default function!") end

or use a metatable as shown in another answer.

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

Related