This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
sEi's profile picture

[LUA] - DIM A(X1,X2,X3) as table

Started by sEi, 12 July 2014 - 10:58 PM
sEi #1
Posted 13 July 2014 - 12:58 AM
Hehe

Is looking at some old code from my start into programming. We are back in late 80's and i used a Apple II running Integer Basic.

I want to test some old code and need to make a rough translation into LUA, and then later rewrite the code in proper LUA. (I just started into LUA some month ago)

My question is:
To 'simulate' a multi DIM like this:
DIM A(X1,X2,X3)

Is this the right way to do it? or is there a simpler way…?

local X1=10
local X2=10
local X3=10
local A={}
for i=0,X1 do
  A[i]={}
  for ii=0,X2 do
	A[i][ii]={}
	for iii=0,X3 do
	  A[i][ii][iii]=""
	end
  end
end

Then i can access the array like this
A[2][4][3]="some data"

Flashback to look at old old code :)/>

/sEi
Edited on 12 July 2014 - 11:07 PM
theoriginalbit #2
Posted 13 July 2014 - 04:38 AM
yes that is the correct way to do it. though you'd start at index 1, with the way for loops work in Lua if you start at index 0 you'll end up with 1 extra entry. though for readability sake I'd probably suggest renaming your variables.


local function table3d(xSize, ySize, zSize)
  local t = {}
  for x = 1, xSize do
    t[x] = {}
    for y = 1, ySize do
      t[x][y] = {}
      for z = 1, zSize do
        t[x][y][z] = ""
      end
    end
  end
  return t
end
sEi #3
Posted 13 July 2014 - 04:41 AM
[truncated]… in Lua if you start at index 0 you'll end up with 1 extra entry….

I was wondering about how the zero was handled. In the old basic, arrays where zero indexed. Many thanks for the clarification.

The variable names was just an example.

/sEi
Edited on 13 July 2014 - 02:43 AM
theoriginalbit #4
Posted 13 July 2014 - 04:57 AM
well you can index tables by any index you want, including negative numbers, but the thing to be aware of is that indexes less than or equal to 0 are stored as key/value pairs, meaning they're not accessible via the ipairs iterator, they're only accessible via direct access — e.g. t[0] — or via the pairs iterator — in this case they will be out of order, they'll appear after the last numerical index, and mixed in with any key values.