Jhon Zoidberg
Jhon Zoidberg

Reputation: 7

Can you use a variable as a table key? [Lua]

I want a user input as an io.read then I want use that variable as key for a table. I have little knowledge of programming

Is this possible?

EDIT

For example

Alpha = {}

print("foo")
Table1 = io.read()

Table1 = tonumber


print(Alpha.Table1)

Thank you!

Upvotes: 0

Views: 1566

Answers (2)

C0b0ll
C0b0ll

Reputation: 207

Try this :

myTable= {"a", "b", "c"}
i = tonumber(io.read())
if i >= 1 and i <= #myTable then
    print(myTable[i])
end

Upvotes: 0

Paul Kulchenko
Paul Kulchenko

Reputation: 26794

Yes, you need to put that variable in square brackets:

local input = io.read() -- get the value from the user
print(tbl[input]) -- access key in "tbl" based on value in "input"

Upvotes: 2

Related Questions