Can't access functions from module

Hello, I have a player script containing: require “assets.scripts.gamePhysics”, however, when I try to use gamePhysics.pr(), the error “attempt to index global ‘gamePhysics’ (a nil value)” pops up, i have no idea why gamePhysics is nil.

inside gamePhysics.lua there is only a function pr that does print(1)

How do you require it?

E.g.

local gamePhysics = require "assets.scripts.gamePhysics"
1 Like

Thank you for your reply, I tried saving it to a local variable and use gamePhysics.collide(), another error pops up: “attempt to index upvalue ‘gamePhysics’ (a boolean value)” how is gamePhysics a boolean???

I initially used

require "assets.scripts.gamePhysics"

chnged it to

local gamePhysics = require "assets.scripts.gamePhysics"

and the error above^^ showed up

What do you return from the gamePhysics script?

nothing, just

function pr()
   print(1)
end

Try doing:

local M = {}

function M.pr()
    print("hello")
end

return M
1 Like

I’ll try that

Thank you, that worked, if you have time can you please briefly explain why I need to do that? Thx.

In short require returns the value you return at the module’s global scope. If there is nothing, it seems it returns a bool.
I didn’t find anything in the official Lua documentation (anyone?) though.

1 Like

Thanks

Lua 5.1 Reference Manual: require

@sodaJar There’s nothing special about code inside of a module. Nothing secret is going on behind the scenes. When you ‘require()’ a file, it runs the code in that file and returns what the file returns (or ‘true’ if it returns nothing). If you return a table, you get a table. If you return a function, you get a function. If you return ‘5’, then that’s what you get, or ‘vmath.vector3(-23, 45.03, -1)’—what you return is exactly what you’ll get.

What this does:

function pr()
   print(1)
end

Is define a global function named ‘pr’. It doesn’t put it in a table for you, it just defines it in the global scope (as it would in any .script or .gui_script file as well).

It’s just a convention that lua files usually return a table of functions and values. But that’s something that the author does on purpose, it doesn’t get done for you automatically.

2 Likes

Thanks a lot