Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How to I run functions inside a Table?

Asked by 6 years ago

So i'm trying to make a function run inside a Table, Here's my table:

Functions = {
[1] = Test("Hello!"),
}

And here's my simple function:

function Test(String)
    print(String)
end

So yeah, how would I do it? I already tried doing this:

Functions[1]

But that didn't work .(Sorry if that's a dumb mistake, i'm not really good at scripting..)

2 answers

Log in to vote
1
Answered by 6 years ago
Edited 6 years ago

Your first script segment can be evaluated like this:

Functions = {
[1] = Test("Hello!"),
}
--[1] is the same as this:
Functions = {Test("Hello!")}
--Test("Hello!") asks lua to run the function. Test calls 'print' but doesn't return anything, making this line evaluate to:
Functions = {}

Clearly this isn't what you want. If you want Functions[1] to print "Hello!", use an anonymous function:

Functions = {
    [1] = function() Test("Hello!") end,
}
--Usage:
Functions[1]()


--Or don't use an anonymous function:

Functions = {
    [1] = Test      --Notice how we don't call it here, we just assign it to index 1 of the table
}
--Usage:
Functions[1]("Hello!")


--Or use Functions like a dictionary:

Functions = {}
Functions.Test = Test
--Usage:
Functions.Test("Hello!")

--If Functions is just supposed to be a list of functions, you don't need the [1] syntax; just do:
Functions = {
    Test,
    Test2,
    function() print("Anonymous function") end,
    --etc
}
--Functions[1] is Test, Functions[2] is Test2, etc
0
Thanks MRbraveDragon 374 — 6y
Ad
Log in to vote
0
Answered by
DanzLua 2879 Moderation Voter Community Moderator
6 years ago
Edited 6 years ago

I setup my functions inside tables like this

local table = {
    func = function()
        print("hey look at me")
    end
}

table.func()

wiki page with examples

0
I read the Wiki already... Is there a way to do it without making the actual function inside the table? I just want to call it from the table. MRbraveDragon 374 — 6y
0
Should work then. hiimgoodpack 2009 — 6y

Answer this question