Method: Difference between revisions

From Legacy Roblox Wiki
Jump to navigationJump to search
>Trappingnoobs
Added how to make a method. May not be completely accurate and/or not beginner friendly enough. Need somone to check it over.
>Flurite
Redirected page to Methods
 
(9 intermediate revisions by 3 users not shown)
Line 1: Line 1:
==Introduction==
#redirect [[Methods]]
 
Methods are functions which belong to a particular object.  Although standard Lua doesn't have them, they're a major focus of Roblox Lua.
Methods act like a function stored within an object.  The method itself is accessed in the same way a Function in a Table is accessed.  However, a special property of methods changes how they are called.
 
These two codes call the same function (a) with the same parameters (b).
 
<pre>b.a(b)
b:a()
</pre>
 
The second is more brief and concise.  Methods can increase typing speed, because there is less need to retype variable names.
Methods may or may not return data.
 
==Examples==
 
All instances (possibly excluding) some core services, have the remove method, along with the clone method.
Sounds have the Play method and the Stop method.
 
==Making your own==
 
Making your own methods can
*Make your code look cool
*Make your tables more dynamic
 
{{EmphasisBox|This tutorial-like section assumes you have a good knowledge of table terminology and functions.}}
 
First, we need a table to ''apply'' the method to. I'm going to make a checkbox (It doesn't actually DO anything, but it's an application example. Feel free to make this work)
 
<pre>
Checkbox = {
    ["Checked"] = false,
    ["CheckedImage"] = "Image",
    ["UncheckedImage"] = "Image",
    ["ImageButton"] = .,
    ["ChangeState"] = function(s)
        s.Checked = not s.Checked
    end
}
Checkbox.ImageButton.MouseButton1Down:connect(function()
    Checkbox:ChangeState()
end)
</pre>
 
As you can see, rather than just typing
<pre>
Checkbox.ImageButton.MouseButton1Down:connect(Checkbox.ChangeState)
</pre>
I made it call it as you'd call a method.
 
When you call a function as a method, you automatically pass an argument as the TABLE ITSELF. For example,
 
<pre>
function ReturnTable(Num)
    return {
            Num,
            function PrintNum(s)
                print(s.Num)
            end
    }
end
 
Tabl = ReturnTable(5)
Tabl:PrintNum()
</pre>
 
That will output 5 because we passed in the table, so the function will receive the table it's located in. Because we called it as a method, it passed "Tabl" as an argument. You can do it with a dot, but it looks kind of stupid:
 
<pre>
Tabl.PrintNum(Tabl)
</pre>

Latest revision as of 20:28, 23 January 2012

Redirect to: