Log In  

I have lots of different tables for different things.
Adding functions into these tables looks like a good idea, because I can write every update or draw for every type of enemy the same way. Something like this:

for e in all(enemies) do
 e.update()
end

The only thing I want to know, is how can I address the table within it's function?
For example:

enemy =
{
 x=0,y=0,
 update = function()
  [b]--how to address these x and y variables from this update function?[/b]
  x+=1
  y+=1
 end
}

Writing something like e.update(e) seems stupid. Maybe what I'm talking about isn't even possible, I just couldn't find anything on this subject.
Thanks for any help

P#37021 2017-02-01 16:53 ( Edited 2017-02-02 08:01)

You could do something like this, which I think is called a closure:

function make_enemy(x0,y0)
 local e={x=x0,y=y0}
 e.update =function()
  e.x+=1
  e.y+=1
 end
 return e
end

entitylist={}
function _init()
 for i=1,50 do
 add(entitylist,make_enemy(rnd(128),rnd(128))) 
 end
end

function _update()
 for i=1,#entitylist do
  entitylist[i].update()
 end
end
P#37022 2017-02-01 17:07 ( Edited 2017-02-01 22:38)

Exactly what I needed, thanks!

P#37023 2017-02-01 17:15 ( Edited 2017-02-01 22:15)

That works, but has the disadvantage of creating a separate function object in memory for each instance. You might prefer using Lua's approach to object oriented programming. This involves several language features, including dedicated syntax for defining and calling methods, the "self" keyword, and "metatables" for setting up method inheritance.

http://pico-8.wikia.com/wiki/Setmetatable
https://www.lexaloffle.com/bbs/?tid=3342

P#37041 2017-02-01 23:09 ( Edited 2017-02-02 04:09)
1

a third option:

enemy =
{
x=0,y=0,
update = function(self)
self.x+=1
self.y+=1
end
}

note that self is not a special name, it's just a parameter like any other.

then, instead of using the dot method call syntax, you use the colon syntax:

enemy:update()

this is shorthand for passing in the enemy object to its own method, as if you'd done this:

enemy.update(enemy)

if i'm not mistaken, this sounds almost exactly like what you're asking for.

(side note: not well illustrated by this trivial example, but contrary to what the "expanded form" i gave may suggest, the expression to the left of the colon will be evaluated just once.)

P#37043 2017-02-02 00:24 ( Edited 2017-02-02 05:27)

Yeah, I see how it's eating up memory. Better find something more suitable for lua.
Thanks, everybody!

P#37047 2017-02-02 03:01 ( Edited 2017-02-02 08:01)

[Please log in to post a comment]

Follow Lexaloffle:          
Generated 2024-03-29 06:46:03 | 0.006s | Q:17