Tables (SOLVED)

Hi,

Is there a way for my instance gameobject to choose from a random position (a-i) from my lua table and once it got a random position it must remove the position from the lua table so that my other instance gameobjects can’t use the same position. I also want to insert the position back into the lua table once the gameobject gets destroyed.

Lua table:

local M = {}

M.planet_position =
{
	a = {x_axis = 0, y_axis = 0}
	b = {x_axis = 0, y_axis = 0}
	c = {x_axis = 0, y_axis = 0}
	d = {x_axis = 0, y_axis = 0}
	e = {x_axis = 0, y_axis = 0}
	f = {x_axis = 0, y_axis = 0}
	g = {x_axis = 0, y_axis = 0}
	h = {x_axis = 0, y_axis = 0}
	i = {x_axis = 0, y_axis = 0}
}
return M

First you are missing ,s at the end of those table lines for each letter.

If you set a letter to nil ( a = nil ) it will remove it from the list.

You will want to keep a second copy of the table to restore the first one’s values. Probably can do it with a Lua table shallow copy function of the primary one. Then you will need to reference each letter when you create or destroy the gameobjects so that you know what to restore.

Is there a reason you are referencing each sub table by a letter? You could do

local planet_positions =
{
    {planet = "a", x_axis = 0, y_axis = 0},
    {planet = "b", x_axis = 25, y_axis = 14},
    {planet = "c", x_axis = 1, y_axis = 2}
}

print(table.remove(planet_positions, 1).planet)

planet_positions_saved = {}
local random_number = math.random(#planet_positions)
print(random_number)
print(planet_positions[random_number].planet)
local planet = table.remove(planet_positions, random_number)
table.insert(planet_positions_saved, planet)
print(planet_positions_saved[1].planet)


Then it would be easier to get a random planet and also move them around between tables.

3 Likes

I think I will go for the last bit of code. It is a bit easier to understand.
I don’t know I referenced each sub table by a letter. Actually unnecessary. Now I understand better.

Thank you!

How would I go about changing the “x_axis” and “y_axis” values for each one because I do bit of calculations using screen height/width along with other values that will determine each axis.

You would need to loop through the table looking for the value with the planet id you wanted to modify.

for k, v in ipairs(planet_positions) do
    if v.planet == "a" do
        planet_positions[k].x_axis = 9
    end
end


You can make a function you do that for you and you just pass the id and what values to change to the helper function.

2 Likes