Jump to content




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


  • You cannot reply to this topic
3 replies to this topic

#1 sEi

  • Members
  • 41 posts

Posted 12 July 2014 - 11:58 PM

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 by sEi, 13 July 2014 - 12:07 AM.


#2 theoriginalbit

    Semi-Professional ComputerCrafter

  • Moderators
  • 7,332 posts
  • LocationAustralia

Posted 13 July 2014 - 03: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


#3 sEi

  • Members
  • 41 posts

Posted 13 July 2014 - 03:41 AM

View Posttheoriginalbit, on 13 July 2014 - 03:38 AM, said:

[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 by sEi, 13 July 2014 - 03:43 AM.


#4 theoriginalbit

    Semi-Professional ComputerCrafter

  • Moderators
  • 7,332 posts
  • LocationAustralia

Posted 13 July 2014 - 03: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.





3 user(s) are reading this topic

0 members, 3 guests, 0 anonymous users