Jump to content

Problems with tables


Simi23

Recommended Posts

Hi there! There is my code, but it doesn't work good. My goal is to list 5 random strings in the chat but the first in the chat is always "nil". Why?

local pizzas = {"Hawaii", "Sonkás", "Sajtos", "Tonhalas", "Négysajtos"}
local deliver = {}

function starter()
        local counter = 1
        while counter <= 5 do
            local num = math.random(0,4)
            counter = counter + 1
            table.insert(deliver, tostring(pizzas[num]))
        end
        setTimer(
        function ()
        outputChatBox("Megkaptad a rendelést, most szállítsd le a következő pizzákat: "..tostring(deliver[0])..", "..tostring(deliver[1])..", "..tostring(deliver[2])..", "..tostring(deliver[3])..", "..tostring(deliver[4]).."!")
        end ,5000,1)
end

addCommandHandler("deliver", starter)

 

Link to comment

Arrays in lua start at index 1, so at line 13 when you are outputting deliver[0] the value will be nil

Also change at line 7 the random argument to 1,5

Another optional thing is to convert the while loop at line 6 with a for loop

 

The code should be this (not tested):

local pizzas = {"Hawaii", "Sonkás", "Sajtos", "Tonhalas", "Négysajtos"}
local deliver = {}

function starter()
	for counter=1,5 do
		table.insert(deliver, tostring(pizzas[math.random(1,5)]))
	end
	setTimer(
		function()
			outputChatBox("Megkaptad a rendelést, most szállítsd le a következő pizzákat: "..tostring(deliver[1])..", "..tostring(deliver[2])..", "..tostring(deliver[3])..", "..tostring(deliver[4])..", "..tostring(deliver[5]).."!")
		end,
    5000, 1)
end
addCommandHandler("deliver", starter)

Note that in deliver there could be duplicates of one item of pizzas, and some items could not appear. Not sure if this is a problem for you anyway, maybe this is what you want. Just wanted to make sure you know this. 

Hope it solved your problem :)

Edited by LoPollo
added code
Link to comment

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...