Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

Why does this print the name of the table?

Asked by
LuaXYZ 5
8 years ago

Anyone know?

local core = {
    ShowChats = function(name)
        print(name)
    end
}
core:ShowChats("Hello people")
0
You can fix this by replacing the ':' with the '.' but i cannot explain why as i dont work with tables like this in Lua. User#5423 17 — 8y

1 answer

Log in to vote
3
Answered by
M39a9am3R 3210 Moderation Voter Community Moderator
8 years ago
Edited 8 years ago

Table Functions; Methods vs. Functions

With Lua, we're able to execute functions within tables. Functions, of course, can be run two ways when in tables, however. Functions inside tables can be run by simply calling the function as if it were independent or calling the function as a method as if it were reliant on the table it's in.

With methods, you must keep in mind that the first argument of the function will be utilized by the table it is being called from. Thus why you are receiving your table value. This may be helpful if you are trying to gather information that is within the table itself.

local PointsController = {
    RedTeamPoints = 50;
    BlueTeamPoints = 75;
    GetTeamPoints = function(self, Team) --Self becomes the table in this example, the Team is the string that is used when called.
        if Team == 'Red' then
            return self.RedTeamPoints
        else
            return self.BlueTeamPoints
        end
    end;
}

PointsController:GetTeamPoints('Blue')

With calling the function as a method, the script will automatically recognize the table as a table.

Trying to call the function as normal PointsController.GetTeamPoints() will throw an error claiming that self has not been defined. It's that subtle difference between how the functions are executed that will depend on whether the script will run or break. I can actually understand this as we have methods for Roblox objects as a means to identify what objects we want to alter.

The simple solution to your specific problem is (unless you want to utilize the table with a method) just change the method to a function.

local core = {
    ShowChats = function(name)
        print(name)
    end
}
core.ShowChats("Hello people") --Just simply change from a colon to a period.

You can find more information on these methods.

Hopefully, this answered your question and if it did do not forget to hit the accept answer button. If you have any questions, leave them in the comments below.
0
Thanks very much! LuaXYZ 5 — 8y
Ad

Answer this question