Change code based off variables

  1. What do you want to achieve? i want to change the code that is run based off a variable, refer to example code
local function code1()
	print("text")
end
local function code2()
	task.wait(1)
end

local number = 2

code[number]()

the code above does not work; how do i make it so "code{number}() is interpreted as “code2()”

if number == 1 then code1()
elseif number == 2 then code1() end

without doing this?

You can use tables for that, here:

local function code1()
	print("text")
end
local function code2()
	task.wait(1)
end

local code = {code1, code2}
local number = 1

code[number]() -- Will print "text"
3 Likes

neat, didn’t think of that. Thanks a ton!

1 Like

another thing you can do is enclosures which let you generate functions at runtime (ie changing code based off variables):

function enclosure(a)
    local function newfunc(b)
        return a + b
    end
    return newfunc
end

local enclosedfunc = enclosure(2)
print(enclosedfunc(2)) -- outputs 4
1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.