function in table?

Discuss using and improving Lua and the Lua Player specific to the PSP.

Moderators: Shine, Insert_witty_name

Post Reply
the underminer
Posts: 123
Joined: Mon Oct 03, 2005 4:25 am
Location: Netherlands

function in table?

Post by the underminer »

I want to be able to store functions in tables like

Code: Select all

special = {1,2,3,enemies()}

if X == 2 then
      special[4]
end
It doesn't work like described above, though. Anyone knows how to do this?
Behold! The Underminer got hold of a PSP
KawaGeo
Posts: 191
Joined: Sat Aug 27, 2005 6:52 am
Location: Calif Mountains

Post by KawaGeo »

Try this:

Code: Select all

special = {1,2,3,enemies}

if X == 2 then
      special[4]()
end
Geo Massar
Retired Engineer
the underminer
Posts: 123
Joined: Mon Oct 03, 2005 4:25 am
Location: Netherlands

Post by the underminer »

That nearly works, but at the same time it doesn't.
Luaplayer doesn't give an error on storing 'enemies' (without quotation) in a table, but when calling special[4]() it gives an error: problem indexing field '?' (a nil value). I checked that i = 1 and enemies was stored on place 4. What to do?
Behold! The Underminer got hold of a PSP
KawaGeo
Posts: 191
Joined: Sat Aug 27, 2005 6:52 am
Location: Calif Mountains

Post by KawaGeo »

For the two dimensional array, you need to create a table within a table. Did you do that?
Geo Massar
Retired Engineer
the underminer
Posts: 123
Joined: Mon Oct 03, 2005 4:25 am
Location: Netherlands

Post by the underminer »

Code: Select all

Enemy = {}
Enemy[1] = {13,5,0,0,1,0,12,17,1,30,0,enemies}

function CalcEnemy()
i = 1
print(Enemy[i][11]) -- this works, gives 0
Enemy[i][12]() -- error here
end

function enemies()
(..) -- big ass function here
end
Yeah, it seems I did
Behold! The Underminer got hold of a PSP
KawaGeo
Posts: 191
Joined: Sat Aug 27, 2005 6:52 am
Location: Calif Mountains

Post by KawaGeo »

I see you did alright but...

The function 'enemies' should be moved above in order to declare it sooner than using it.
Geo Massar
Retired Engineer
romero126
Posts: 200
Joined: Sat Dec 24, 2005 2:42 pm

Post by romero126 »

variable = function (param) do stuff here; end
KawaGeo
Posts: 191
Joined: Sat Aug 27, 2005 6:52 am
Location: Calif Mountains

Post by KawaGeo »

Both function syntax work the same but the latter makes more sense if it is used as a variable.
Geo Massar
Retired Engineer
the underminer
Posts: 123
Joined: Mon Oct 03, 2005 4:25 am
Location: Netherlands

Post by the underminer »

KawaGeo wrote:I see you did alright but...

The function 'enemies' should be moved above in order to declare it sooner than using it.
You're absolutely right... And I thought I wasn't a noob anymore. Works fine now, thanks 2 all
Behold! The Underminer got hold of a PSP
Post Reply