Coding things you probably didn't know (part 1)

thanks for explaining me what break does

1 Like

Did you know? You could set a dictionary key and value in a function after it has been written but before you call it?
For example

local function p()
print(msg)
end
getfenv(p).msg="Msg"
p()
-- "Msg"
2 Likes

Well please try to put apostrophes in necessary places
It’s commas not comma’s Comma does not own anything

1 Like

what is msg equal too??? is msg supposed to be a parameter of p

msg is a variable that doesn’t exist inside the p function. getfenv(p).msg = "Msg" adds msg to the environment and sets it’s value.

1 Like

What’s the point of continue? Doesnt return do the same?

1 Like

idk why don’t you check?

it does not do the same. return stops the function and continue skips the iteration. if you have this code:

for i = 1, 5 do
	if i == 2 then
		return
	else
		print(i)
	end
end

then it will only print 1, but if you write continue instead of return, it will print 1, 3, 4 and 5. Skipping 2

1 Like

continue is way different from return.

return ends a function.

continue skips a loop in pairs.

If you do return instead of continue in a loop, it’ll end the function it’s used in, or the function the loop is in.

2 Likes

how come when i tested this it didnt stop the whole function?

how come it didnt end for me???

Returning, it doesn’t print "ended", and stops when it’s 2 keys from the last.

image

Continuing, it prints "ended" but skips key 2.

(continue in Luau is goto in Lua)

image

1 Like

ngl i knew it was weird that they would do the same thing

1 Like

I normally use return to end a function in a loop, bringing it to the next loop. Am I doing something wrong?

No, to end a function, you use the return, which you are doing correctly.

[...]:Connect(function()
	for i,v in pairs(...) do
		...
		if ... then
			return -- ends the entire function
		end
	end
end)

[...]:Connect(function()
	for i,v in pairs(...) do
		...
		if ... then
			[...]:Connect(function()
				return -- ends ^^this function
			end)
		end
	end
end)

for i = 1,5 do
	if i == 4 then 
		continue -- this will skip if i == 4
	end
	print(i) --> 1,2,3,5
end
2 Likes

To add on, semicolons can also be used as a line break on a single line.

local var1 = 1; local var2 = 2; print(var1+var2)

This can be useful in shortening code so you don’t have hundreds of tiny, menial lines that make your scripts a burden to scroll through.

2 Likes

this is definitely gonna be in part 2

1 Like

Also, you can just do this instead:

local var1, var2 = 1, 2; print(var1 + var2)
1 Like

but are the values different. for ex-

_G.id = 13523532
shared.id = 22432532
print(_G.id)
print(shared.id)

wull this gimme 2 different results

1 Like

there’s no need for the semi-colon

local var1 = 1 local var2 = 2 print(var1 + var2)

this works just as fine