0

I am new in Lua and I want to try display an item from an array, but it's like an array inside an array.

This is my list:

local itemlist = {
    { name="blue car", price=5000 },
    { name="red car", price=10000 },
    { name="green car", price=2000 }
}

And so if I would input the text "red car" I want it to output something like this:

The red car costs 10000 dollars.

How can I do this in lua? So far I have only found some string match examples where I can see if an array contains an item, but what I want is to output that AND the price. How do I get to the price? I have no idea where to even start.

2 Answers 2

2

You should read about tables and tables with sequences in the manual. Then you can decide whether to use pairs or ipairs to iterate over the table.

Another approach, if the names are going to be unique, would be the change the structure:

local itemlist = {
    ["blue car"] = { price=5000 },
    ["red car"] = { price=10000 },
    ["green car"] = { price=2000 }
}

-- or even 

local prices = {
    ["blue car"] = 5000,
    ["red car"] = 10000,
    ["green car"] = 2000
}

print(itemlist["red car"].price);
print(prices["red car"]);
Sign up to request clarification or add additional context in comments.

Comments

1

You don't need pattern matching in your simple example.

local str = "red car"
for _, v in ipairs(itemlist) do
    if v.name == str then
        print("The " .. v.name .. " costs " .. tostring(v.price) .. " dollars.")
    end
end

5 Comments

It works great on the first item in the list, but the second ones (red car and green car) won't get printed out. I typed in "blue car" and it displayed it perfectly. Ohhhhhhhhh nvm it works now! THANKS!!!!
By the way, how can I make the "str" check if the item is in the list. Instead of setting local str = red car", like if I type in ANY of the items names it would recognize it. And if the item is not in the list, like a Purple Car, it will say "i dont have that car in stock."
@aliazik Use a boolean flag like local found_car = false, if a name matches, sets it to true and break out of the loop. Check its value when the loop is done.
The thing is, I am doing this for a little game. And the text I type in is stored in a variable called m.content . So what I need to do is, if the player types "red car", it will then set the local str = "red car" . But I don't want to add a long if-statement like if (m.content == 'red car') then local str = "red car" elseif (m.content == 'blue car') then local str = "blue car" end . That would take so much time to make if my list contains 1000 items for example
Nevermind, I solved it now! elseif (table.find(itemlist, m.content:lower(), 'name')) then

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.