Is putting local variables inside of a function bad practice

as stated in the title

Every time I read code on the Developer forum, I see people misusing local and placing them inside functions. Is this a terrible idea, or are there any benefits to doing so? I nearly always utilize globals inside functions that are specified in parameters.

i personally believe this is a bad idea but i want to hear what other have to say
here is some examples

Wrong

local function Foo()
local Something = 5
end)

correct

local function Foo(Something)
Something = 5
end)

i am open to discuss this

1 Like

Probably. Especially if you need to get the variable outside of the function. But in that case you could use getfenv()

yeah i agree but getfenv() is used by some hackers so it’s kind of sketchy

1 Like

No, using local is proper. You should always use it. The only case where you wouldn’t use local is if you wanted to use getfenv or if you had more than 200 local variables in a scope. Neither of those should ever happen if you’re programming right. Feel free to ask me to elaborate on anything if you want, I’m on mobile right now so I’m a little slow to type.

3 Likes

you should always use local variables

local variables are faster
local variables are harder for hackers to see in the bytecode
find out more here
http://lua-users.org/wiki/LocalsVsGlobals

if you want to use a variable outside and inside a function simple define the variable at the top of the script

local myVar = "Hello World!"

local MyFunction = function()
	myVar = "Value has changed"
end

MyFunction()

print(myVar)

then what about parameters are they needed

Thank you! i have been coding in lua for nearly a year and i just learnt something new

1 Like

parameters are also local variables her is a demo with parameters

local myVar = "Hello World!"

local MyFunction = function(valueToAdd)
	myVar = myVar .. valueToAdd
end

MyFunction("Add this value")

print(myVar)

Hackers also use script.Parent, localscripts, and workspace, is that sketchy?

1 Like