so i've been ticking with the self
keyword in lua,
I am assuming that the self
keyword works very much like the this
keyword in javascript, but i guess i could be wrong, since whenever I try to index a value from it, lua throws an error
tha's like this
attempt to index global 'self' (a nil value)
and here is my code;
local account = { name ="Roblox", sonsName = self.name.." jr", --error? get = function() return self.name --error? end } print(account.get())
I tried making a closure to see if it'll get rid of the global
part in the error,
but it's no use:
here is the code
local account = (function() local account = { name ="Roblox", sonsName = self.name.." jr", --attempt to index 'self' a nil value get = function() return self.name --attempt to index 'self' a nil value end } return account end)() print(account.get())
It is important to clarify that self
is not a keyword, but a variable
. The reason why quite a vast number of people tend to make this error is because ROBLOX highlights self
as a keyword. This is incorrect.
Now to answer your question, we use self
as a way to access the previous argument called in the function, without passing the argument explicitly. self
is notably used in Object Oriented Programming Implementation in Lua.
Consider the following example.
local t = { message = ""; } function t.set_message (self, message) print(t); t.message = message; print(message); end t.set_message (t, "Hello World"); t:set_message ("Hello World");
Notice how when I used :
(colon) symbol, I did not pass the table t
as an argument.
Let me help you out with your example now. Consider using getters and setters
-- [Declaration Section] local account = { name = ""; }; -- [Procedure Section] function account.set_name (self, name) self.name = name; end function account.get_name (self) return self.name; end -- [Output Section] account:set_name("Zafirua"); print(account:get_name());
For in depth detail on why exactly we use it and its purposes, please consider reading the ROBLOX Dev wiki or Lua Reference Manual 5.1 +
In addition to the fact that self
is implicitly passed to a function when using the colon syntax (i.e. account:get_name()
), it's worth noting that self
can also be implicitly received as a function argument using a similar syntax. I'll build upon Zafirua's excellent answer to provide an example here:
local account = { name = ""; }; -- [snip] -- This declaration is equivalent to the original function account:get_name() return self.name; end
In programming terminology, we call this "syntactic sugar".
hmm.... try
local account = { name ="Roblox", sonsName = self.name.." jr", --error? get = function() return account.name end } print(account.get())