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

Can you call a table from a module script?

Asked by 6 years ago

Is it possible to have a table with say "Level = 1", "Gold = 5" by default which i later then copy to the player, which could be called from a server script from something like module.table?

0
can you explain that better? User#20388 0 — 6y

2 answers

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

You can't "call" a table. When require()ing a module script, it is executed once per machine, and the return value is cached. Since table's are objects in Lua, a reference to the table is returned. Therefore if you try to require() the same module script multiple times in the same environment, the return value from the first invocation is returned, and so the same table will always be returned.

Example

Module Script

local tab = {
    x = 7,
    y = 2
}

print("foo")

return tab

Server Script A

local Module = require(game.ServerStorage:WaitForChild("ModuleScript"))

Module.x = 4

Server Script B

local Module = require(game.ServerStorage:WaitForChild("ModuleScript"))

Module.y = 2

Server Script C

wait(1)
local Module = require(game.ServerStorage:WaitForChild("ModuleScript"))

table.foreach(Module, print)

Explanation

In the examples above, the module script will only be executed once, hence foo will only be printed once even though the module script is required three times on the same machine (the server). Assuming Script A and Script B require the module before C, the same table will be modified and the x and y fields, respectively, will be changed. Once C requires the module and prints its contents, the output should be:

foo
x 4
y 2
Ad
Log in to vote
0
Answered by 6 years ago
Edited 6 years ago

Yes you can call values from scripts. After requiring the table like in module script:

table = {"poo", 1, false}

and then in server script

local module = Require(game.WHEREVERYOURMODULESCRIPTIS)

print(module.Table)
--or alternatively loop through it and put it in your own table in this script

myTable = {}

for i,v in pairs(module.Table) do
    table.Insert(v) --inserts values from module table to "myTable"
end

for i,v in pairs(myTable) do
    print(v)
end

--returns poo, 1, false

Answer this question