2

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
  • 1
    Check to be sure that tab[userData] returns non-nil before attempting to make a function call with the result. Commented Jan 28, 2021 at 1:27
  • You're right. Thanks. Commented Jan 28, 2021 at 5:02

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.