Crisiiii
Crisiiii

Reputation: 409

pass an array objects in Corona with class

I'm creating an app with Corona structured in Class and I have a problem when I want pass an array objects for create an object. I have this:

main.lua

local SurpriseBoxClass = require("SurpriseBox")
local BoxClass = require("Box")

local box1 = BoxClass.new('palo', 'images/chestClose.gif', 'OPEN')
local box2 = BoxClass.new('moneda', 'images/chestClose.gif', 'OPEN')
boxes = { box1, box2 }

local game = SurpriseBoxClass.new(boxes)

SurpriseBox.lua

local SurpriseBox = {}
local SurpriseBox_mt = { __index = SurpriseBox }

function SurpriseBox.new(boxesAux)
 local object = {
   boxes = boxesAux
 }
 return setmetatable( object, SurpriseBox_mt )
end

The problem is when I want to print the content of array in a method of SurpriseBox, and the program said me that the array is nil if for example I do this:

print(boxes[0])

What can I do?

Thanks!

Upvotes: 2

Views: 141

Answers (2)

HennyH
HennyH

Reputation: 7944

Look at the function SupriseBox.new(boxesAux) (where I gather you desire to do the printing):

In object, you are associating the key "boxes" with the table boxesAux. This to access the contents of boxesAux via object you must go through the following process:

object["boxes"] or object.boxes will get you to boxesAux, to go into that you need the superscripting i.e [1]

print(object["boxes"][1]) --etc..
print(object.boxes[1]) --etc..

Note that, this will now give you box1. If you want to print a meaningful display of it's content (that is if the class isn't overloaded) you should use a pretty printing library.

Upvotes: 0

Ray Osgod
Ray Osgod

Reputation: 64

Lua tables are 1-based.

Try print(boxes[1], boxes[2]).

It will print the table id. If you need to print the contents of the table, you must iterate over its fields, or use a custom printer that does it for you (see "Print a table recursively").

Upvotes: 2

Related Questions