• There is NO official Otland's Discord server and NO official Otland's server list. The Otland's Staff does not manage any Discord server or server list. Moderators or administrator of any Discord server or server lists have NO connection to the Otland's Staff. Do not get scammed!

Again, question about loops.

Hermes

dziwki kola gramy w lola
Joined
Nov 17, 2007
Messages
1,867
Reaction score
14
Location
Poland
Hi there :D.

I have extended my skills in LUA scripting with simple for loops.

Now my imagination goes further and now I have request for more advanced loop usage.

1. I have table.
Code:
local table = {
{number = 1, name = "One", value = 11},
{number = 2, name = "Two", value = 22},
{number = 3, name = "Three", value = 33}
}
And I want to get variables "name" and "value", but those variables must depend on "number".

Humm, let me give you example of script that might use those items from table.
Code:
local table = {I have posted table up.}

function text()
--perhaps here should be loop for table
	broadcastMessage(number .. ", " .. name .. " and " .. value)
	return TRUE
end

Ofcourse I can use something like this:
Code:
if(number == 1) then
	name = "One"
	value = 11
elseif(number == 2) then
	name = "Two"
	value = 22
elseif(number == 3) then
	name = "Three"
	value = 33
end
But it's cleaner with table, right?


2. Second question is.. what's the main difference between loop "in pairs()" and "in ipairs()"?


Thanks in advance & regards,
Hermes
 
Last edited:
Programming in Lua : 7.3

According to this table:
Code:
local table = {
{number = 1, name = "One", value = 11},
{number = 2, name = "Two", value = 22},
{number = 3, name = "Three", value = 33}
}
You can do it like that:
Code:
local rand = math.random(1, 3)
for _, value in pairs(table) do
    if rand == value[1] then
        broadcastMessage(rand..", " ..value[2].. " and "..value['value'])
        break
    end
end

You can also try like this:
Code:
local rand = math.random(1, #table)
broadcastMessage(table[rand][1]..", " ..table[rand][2].. " and "..table[rand]['value'])

Im not sure about value['value'], but my guess is that should work tho.
 
Last edited:
Back
Top