1
votes

I am trying to write a lua switch, based on what I have read so far it seems this is achieved by using a table. So I made a really barebones table but when I try to run it I get an error saying table index is null.

Ultimately what I want is based on different input, this code should call on different lua files. But for now since I am new to this language I figured I would settle for not having that index error.

thanks

#!/usr/bin/lua

-- hello world lua program 
print ("Hello World!")

io.write('Hello, where would you like to go?\n')
s = io.read()
io.write('you want to go to ',s,'\n')
--here if i input a i get error
location = {
  [a] = '1',
  [b] = '2',
  [c] = '3',
  [d] = '4',
}

location[s]()

Above is the code that I got so far. Below is the error.

~$ lua lua_hello.lua 
Hello World!
Hello, where would you like to go?
a
you want to go to a
lua: lua_hello.lua:11: table index is nil
stack traceback:
    lua_hello.lua:11: in main chunk
    [C]: in ?

The table code is based on this example here: Lua Tables Tutorial section:Tables as arrays

2

2 Answers

2
votes

What appears to be the issue is that location[a] is setting location at index a, which is not a string. When you enter a into your input, it gets read as 'a' which IS a string. Index [a] is different from index ['a']. What you want is to replace your assignments so that they're assigned to strings (location['a'] = '1').

As Ihf has said, if you want to print the output then you need to call print(location[s]) because location[s] will simply return the string '1' (or whichever value, just as a string). If you want to assign the numeric value (to use for calculations or etc) then you should use location['a'] = 1. Alternatively, keep the value as-is as a string and when you attempt to use the value, simply use tonumber(). Example: x = 5 * tonumber(location[s]).

I hope this was helpful, have a great week!

1
votes

Try

location = {
  ['a'] = '1',
  ['b'] = '2',
  ['c'] = '3',
  ['d'] = '4',
}

Then that error goes away but is replaced by attempt to call a string value (field '?') because location['a'] is the string '1'.

Perhaps you want

print(location[s])