Question

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?

Was it helpful?

Solution

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top