1
votes

I have been working on a simple component based c++ and lua game engine. Currently all the subsystems like audio and physics can be called from lua with there own module using luaL_newlib.

The problem I am having is how can a lua script call functions to modify its entity. Like SetPosition() is obviously going to need to be called on the instance of an entity rather than static functions. So is there a way I can have these instanced functions.

One idea I had was each entity registering functions for itself with a module name that is unique to it. So it would look like entity1.Setposition and entity2.Setposition. Would it be possible to register, effectively duplicate functions like this?

Or is there another way to have instanced functions like this so components can modify the entity that they are a part of?

If I have explained myself badly please do say so I will gladly provide more information

1

1 Answers

3
votes

Lua has syntactic sugar for "instance methods." If you call a function with a colon instead of a dot, like this:

entity1:SetPosition(...)

then Lua rewrites it to this:

entity1.SetPosition(entity, ...)

In other words, it adds an implicit first argument which is the object that the method is being called on. On the C side, you just see an extra argument. This is the preferred way to make instance methods.


Two other noteworthy things: the rewrite above isn't exactly what happens. If you do something like this:

SomeFunctionReturningEntity():SetPosition(...)

it doesn't rewrite it to

SomeFunctionReturningEntity().SetPosition(SomeFunctionReturningEntity(), ...)

It actually just calls the function once, as you'd expect.

Also, if you're writing an instance method from Lua itself, not from C, there's syntactic sugar for declaring one:

function entity1:SetPosition(...)
end

This is equivalent to:

function entity1.SetPosition(self, ...)
end

i.e. it adds the implicit first argument to the function, and calls it self.

(Incidentally, that's also equivalent to this:

entity1.SetPosition = function(self, ...)
end

Technically, even declaring a function inside of a table is syntactic sugar.)