I'm a new programmer in lua, and there are lots of things I still probably don't know about. I googled what self is in lua, but I still don't understand it. If anyone could give me the easiest explanation for what "self" does in lua, it would be really helpful.
self is just a variable name. It is usually automatically defined by Lua if you use a special syntax.
function tbl:func(a) end
is syntactic sugar for
function tbl.func(self, a) end
That means Lua will automatically create a first parameter named self.
This is used together with a special function call:
tbl:func(a)
which is syntactic sugar for
tbl.func(tbl, a)
That way self usually refers to the table. This is helpful when you do OOP in Lua and need to refer to the object from inside your method.
Similar to this in C++.
Related
Hello everyone!
I've been studying metamethods and I realized something strange!
I already know all the metamethods presented in the Lua documentation as __add, __index, __newindex, etc... But I see around in forums and in questions around here people using metamethods like __ev , __close, __group, and I have never seen anywhere else these metamethods be used or exist in any documentation.
My question is, these metamethods exists? and if not, how are they created? and why people create this metamethods?
anyway, thanks for the attention
These are custom metamethods and have special purpose in specific project or framework.
Metamethods are used to extend functionality of table or userdata. These are most usable to achieve OOP behavior.
Some programmers add custom metatables and metamethods for internal purpose and better readability, such as __super, __extend, __inherit. In most cases such metadata are used from standard metamethods as __index, __call, ... or from routine methods to cleanup objects, error handling and so on.
For example __close could be used with connection or file objects to manage them in predictible way, __gc can't be trusted for this purpose.
Example of __group usage: Lua metatables and metamethod - How to call a different member function
i am new to lua. Recently i encounter a syntax call "extend" in lua, i look up the internet, but nothing can be found.
local item = require "item"
local object = item:extend()
I suspect it is related to inheritance, but no info online. Please help me to clear my doubt or point me to the right resource, thank you.
There is no extend function in standard Lua. The extend function in your code snippet is a user-defined function coming from item. To know what it does, you'd need to look at the source code or documentation for it, not for Lua itself.
Hello
What item:extend() have done is stored in object. So simply check what object is. First with:
print(type(object))
...isit a table, function, number, string, userdata, nil or boolean?
This is a very elementary question about the F# class syntax. Here is a little code to illustrate my problem.
type AClass() as self =
member this.Something = printfn "Hello"
Basically from what I have read the "as self" will create a name to the current instance which can be used in the entire class (like "this" in C# or Java). But "member this.Something" will do the same thing, only that the scope is limited to the method body. I guess I can see when you would use which syntax. The "as self" one can be used if you need it in the constructor or something and you can use the other one if you dont need it in the constructor.
But why do I have to use the "member this.Something" syntax even if I used the "as self" one? Why does it give me an error if I just write "member Something"? What have I missed?
Take care,
Kerr
The scope of as self is the whole class, while scope of this.Something is just an individual method. You don't often need as self since using this.Something is adequate.
Regarding why you need this. in member declaration, I think it's a natural choice since in F# classes you often have let bounds and static methods as well. Having self as default would cause confusion and misuse.
Here is an example using as self in MSDN, which is not common IMO:
type MyClass2(dataIn) as self =
let data = dataIn
do
self.PrintMessage()
member this.PrintMessage() =
printf "Creating MyClass2 with Data %d" data
It sounds like you've got all the differences between global 'as xxx' and member 'yyy.' instance binding sorted out. So I guess the answer to your answer has to be it's "by design".
Folks will argue that there is a deliberate rational behind this "by design" choice, but after 4 years of programming F#, my favorite language by far, I have personally not found it very helpful in any regard.
I suspect that the real reason the language requires explicit instance bindings to variables is because is more closely reflects the underlying .NET CIL implementation. That is, languages like C# bind "this" to the instance of a class definition as a feature. Under-the-hood, both static and instance methods of a class are called in the same manner using the Call and CallVirt opcodes, where in the case of instance methods the address of "this" is loaded as the first argument to the call.
But we've certainly ventured into the territory of taste and opinion.
I don't think this is duplication at all. self's visibility to the entire class is a by-product of F#'s "intelligent" compilation of primary constructors. The constructor's arguments/bindings can be implicitly compiled to both local and member (class-level) fields. The as identifier syntax merely facilitates this references within that mutant context. I'd venture to guess, if unused, it's compiled away. Otherwise, all you've done is stored an extra reference to this as a member field (which would seem bizarre in another language, such as C#).
Say, If i have two or more files using the middleclass extension more or less like this. I omitted some of the obvious middleclass implementation code.
File A:
function Battlefield:initialize()
self.varA
self.varB
end
function Battlefield:attack()
--I want to use self.varA here
end
File B
BattlefieldInstance = Battlefield:new()
function doStuff()
BattlefieldInstance:attack()
end
I know this structure more or less works because i already use it plenty on my project, but my problem is that i want to use these self variables. Normally a self instance is passed between functions inside the same file to do this, but when i do it from another file i obviously can't pass self, because it would be another self, and i need the self from the file where the function is located. Sorry if my question is a bit confusing. I'll try and clarify any questions there are.
I have no idea what middleclass is, but I think you're confusing yourself. The way self works in Lua is a function that looks like function Battlefield:attack() is absolutely the same thing as function Battlefield.attack(self). In other words, self is just an implicit first parameter to the function. And a method call instance:attack() is exactly equivalent to instance.attack(instance) (though it won't evaluate instance twice if you use an expression there).
In other words, BattlefieldInstance:attack() should do exactly what you want.
'self' is a keyword that means 'the current object'. So in the case of Battlefield functions, 'self.varA' inside the function is the same variable as 'Battlefield.varA' outside the function.
Middle Class was a lib that I first saw developed for Love2D; I assuming its the same one that corona is using? (I've used Corona a fair bit... but not Middle Class's OOP system)
either way you can also try using meta tables directly, as so:
---FILE A---
Battlefield= {}
Battlefield.__index = Battlefield
function Battlefield:new()
return setmetatable({var1 = 'somedata', var2 = 'somemodata', var3 = 'lotsodata'}, Battlefield)
end
function Battlefield:attack()
print(self.var1)
end
---FILE B---
BattlefieldInstance = Battlefield:new( )
function doStuff()
BattlefieldInstance:attack()
end
and that'll print out self.var1 (somedata).
Hope this helps!
Why are inline closures so rarely used in Actionscript? They are very powerful and I think quite readable. I hardly ever see anyone using them so maybe I'm just looking at the wrong code. Google uses them in their Google Maps API for Flash samples, but I think thats the only place I've seen them.
I favor them because you have access to local variables in the scope that defines them and you keep the logic in one method and dont end up with lots of functions for which you have to come up with a name.
Are there any catches of using them? Do they work pretty much the same way as in C#.
I actually only just discovered that AS3 supports them, and I'm quite annoyed becasue I had thought I read that they were deprecated in AS#. So I'm back to using them!
private function showPanel(index:int):void {
_timer = new Timer(1000, 1);
_timer.addEventListener(TimerEvent.TIMER, function(event:Event):void
{
// show the next panel
showPanel(index++);
});
The biggest gotcha to watch out for is that often 'this' is not defined in the inline closure. Sometimes you can set a 'this', but it's not always the right 'this' that you would have available to set, depending on how you're using them.
But I'd say most of the Flex code I've worked on has had inline closures rampantly throughout the code--since callbacks are the only way to get work done, and often you don't need the bring out a whole separate function.
Sometimes when the function nested is getting to be too much, I'll break it out slightly with Function variables in the function; this helps me organize a bit by giving labels to the functions but keeping some of the characteristics of inline closures (access to the local variables, for example).
Hope this helps.
One additional problem is that garbage collection is broken when it comes to closures (at least in Flash 9). The first instance of a given closure (from a lexical standpoint) will never be garbage collected - along with anything else referenced by the closure in the scope chain.
I found what originally made me NOT want to do this, but I had forgotten the details:
http://livedocs.adobe.com/flex/3/html/16_Event_handling_6.html#119539
(This is what Mitch mentioned - as far as the 'this' keyword being out of scope)
So thats Adobe's answer, however I am much more likely to need to refer to local variables than 'this'.
How do others interpret Adobe's recommendation ?