Lua `self` Keyword

The self keyword in Lua is not valid in global scope or in a function that isn’t part of a table. It’s simply syntactic sugar for a reference to the current table or object. In Defold scripts, we can use self in every function, for instance init() and update().

Are these standard engine functions internally stored in a Lua table like the following example?

local tbl =
{
    init,
    update,
    ...
}

If this is the case, then it makes sense why using self works in these functions. For example, something like self.velocity would be stored like so:

local tbl =
{
    init,
    update,
    ...
    velocity
}

I don’t know how it works exactly, but scripts work as separate instances that seem similar to tables with how they use the keyword “self”. Scripts aren’t using this in a “global scope”; I personally think of a script as a special lua table. They are also unable to directly reference each other’s variables without external means such as require or go.get.

This should help explain

self is not a syntactic sugar, it’s a regular argument to functions. The colon function notation tbl:method() is a syntactic sugar. init(), update() etc functions are technically simple global functions, but only for the .script parsing/processing sake, they get removed from the global scope after parsing and get stored internally inside the engine in C++. In these functions self is a userdata reference to the C++ object representing the script object, and it acts like a table so you can store your own things inside it.

Because of that you can’t say call self:update(), because update() is not a part of the userdata.
And you can replace update(self) with update(notself) and use notself instead in that function.

3 Likes

Great, this was the answer I was asking for. Thanks.

1 Like

Welcome on the Defold forum! :wave: :grinning:

That’s a really on-topic opinion :sweat_smile: I can’t find anything about such engine :thinking:

You mean Roblox?

Somehow I see you guys went too far from the main topic?

Bro really said “roadblocks” ur not dj Khaled :sob::sob:

What what really makes you think going into a forum of a lua engine just to glaze another lua engine is a giod idea? If we wanted to be in Roblox, we’d be coding in Roblox, but we’re here because we don’t want to do that.