Can someone please explain what the difference is between a local function
[lua]local function doSomething()[/lua]
and a global function
[lua]function doSomething()[/lua]
And when it is best to use them
Same as how 'local' normally works - It means the function only 'exists' and therefore exectutable from that chunk
[QUOTE=NiandraLades;49181959]Same as how 'local' normally works - It means the function only 'exists' and therefore exectutable from that chunk[/QUOTE]
And by the chunk you mean the file?
Indeed - I gotta be honest, I've never actually used local functions but I assume it's for making sure it doesn't conflict with any others of the same name
[lua]-- main.lua
include( "file1.lua" )
include( "file2.lua" )
-- file1.lua
local var = "Hello"
print( var ) -- > "Hello"
local function LocalFunction()
local var2 = "Hola"
print( var ) -- > "Hello"
print( var2 ) -- > "Hola"
end
LocalFunction()
print( var2 ) -- > nil
function GlobalFunction()
print( "Bonjour" )
end
globalvar = "Ni hao"
print( globalvar ) -- > "Ni hao"
GlobalFunction() -- > "Bonjour"
-- file2.lua
print( var ) -- > nil
print( globalvar ) -- > "Ni hao"
GlobalFunction() -- > "Bonjour"
LocalFunction() -- error: attempt to call nil value[/lua]
You should only use locals unless you have a reason to do otherwise - anything global can be accessed by [i]every[/i] other script on the server in the same realm.
[QUOTE=NiandraLades;49182162]Indeed - I gotta be honest, I've never actually used local functions but I assume it's for making sure it doesn't conflict with any others of the same name[/QUOTE]
It's just used for functions that you need to use with recursion/stacking or just functions you don't want being used outside of the file.
Thanks guys.
Sorry, you need to Log In to post a reply to this thread.