Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

It is possible to call a function with the use of arithmetic?

function exeC(func)
	func()
end

while true do
	for i = 1, 10 do
		LO()
		local L = "L"
		local N = i-1
		local LN = L..N
		local LNf = LN.."()"
		wait(0.01)
		print(LNf) -- Used in checking...
		exeC(LNf)
		wait(0.99)
	end
end

What I wanted to happen is to call a function with the use of arithmetic. I find it messy to call a function with lots of if statements (Assigning i value to each function). I have functions named L0 - L9. Is it possible to call a function with arithmetic to match the function's name? e.g (L0 : "L"..[i], i = 0)

I would appreciate your response/answer/help.

2 answers

✓ Accepted answer

You could put them in a table, like this:

local Functions = {L0, L1, L2, L3, L4, L5, L6, L7, L8, L9}

Then call them like this:

Functions[i]()

Where i is the index, from 1 to 10.

1 comment

0

I know how to use tables but I did not know that it could work like this. Thank you for sharing this cool piece of knowledge!

You can technically get away with this by using setfenv to modify the environment of your script, but I'd recommend using a table of functions instead since modifying the script environment is pretty nasty and will also give you tons of warning squiggles.

Table of functions:

local L = {}
for i=0,9 do
    L[i] = func
end

print(L[0]())

setfenv

local env = getfenv(1)--make sure we keep track of the stuff in the current env like script/etc
env["L0"] = function() return 3 end
setfenv(1, env)

print(L0())--L0 will work, but it'll have a warning squiggle since it wasn't properly defined in the script

This discussion is preserved as it was. New answers, comments, and votes are closed.