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

Is this the correct way to define a _G. Function?

Asked by 7 years ago

I'm experimenting with a type of variable/function that is new to me (_G.)

I tried defining a function like this:

_G.function MyFunction() 
--code here
end)

However the script editor gave me a red line, so I changed it to this:

_G.MyFunction = function()
--code here
end)

For my future reference, is the second way the correct way to define _G. functions?

1 answer

Log in to vote
0
Answered by 7 years ago
Edited 7 years ago

When defining functions in any table (_G is a table too), you can do it in two main ways; either like this:

_G.MyFunction = function()
--code here
end)

or like this:

function _G.MyFunction()
-- code here
end)

While this is not related to your specific case of _G, you can also do this:

function MyTable:MyFunction()
-- code here
end)

This will define the function in such a way that the first argument will always be refered to as self, and if you later call the function like MyTable:MyFunction() then the first argument will be the table itself. This can be used for OOP in Lua.

0
Thanks! ShadowsDev 62 — 7y
0
I would not consider lua OO without classes or structures ADeadlyGuest4 62 — 7y
Ad

Answer this question