1

I'm attempting to use a table as a means to do two things at once. For example:

s = passengers -- user input
t = {[3] = car, [7] = bus, [24] = plane, [45] = train}

for k,v in ipairs t do
    if s = k then
        z = v * 10 -- cost per person
    end
end

Now this is extremely basic for what I'm trying to do. I have a list of about 12 items that each have their own number. I want to know if I can do what I did above with the table and provide each of the 12 items with their own key value and then use that ? This key value would represent each items particular, unique number. Also, can I then use that key's value in a later equation, such as above?

3
  • Yes, you can use the lua-tables as hash indexes Commented May 1, 2014 at 22:11
  • 1
    But you cannot use ipairs on a table with "holes" like that. ipairs behaviour is defined only for tables that have contiguous indices from 1 to n. Commented May 2, 2014 at 1:09
  • 1
    Also, unless car, bus, etc. are variables that will create an empty table. You are also missing the ( and ) around t in the ipairs call and you mean == and not = in the if condition. Commented May 2, 2014 at 1:10

1 Answer 1

1

If your keys are unique, your data structure. The point of a table key is direct access to the corresponding value.

This has the same effect as your loop:

local v = t[s] -- value for s or nil if s is not a key
if v != nil then 
    z = v * 10
end

(Or, more exactly the same: local v = rawget(t,s) to account for cases where t has an __index metamethod.)

If we can assume that v will never be false (which would cause an error at false * 10) then it can be written more naturally (which skips that error):

local v = t[s]
if v then 
    z = v * 10
end
Sign up to request clarification or add additional context in comments.

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.