Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable in another module to be used in current module

Here it goes my code

ModuleName.FunctionName.VariableName

I'm wondering if this is applicable, we all know that to load a a function in another module you have to use this code:

ModuleName.FunctionName

I was wondering If my given code is applicable.

like image 940
Liane Avatar asked Dec 14 '25 13:12

Liane


2 Answers

You can use variables in another module, but the syntax is not like ModuleName.FunctionName.VariableName because functions have no fields.

As an example, consider this simple module foo.lua:

local M = {}

function M.func()
    print("calling func")
end

M.var = 42

return M

Note that similar to func(), the variable var must be global, or it's private to the module.

You can use the variable var similar to the way to use the function func():

local foo = require "foo"

foo.func()

print(foo.var)

Output:

calling func
42
like image 121
Yu Hao Avatar answered Dec 16 '25 21:12

Yu Hao


There is two ways you can achieve this.
1 :

-- message.lua
local M = {}
function M.message()
    print("Hello")
end
return M

You can call above module into other file.

-- test.lua
local msg = require "message"
msg.message()

2 :

--message.lua    
msg = "message"

You can call above module by dofile

-- test.lua 
dofile ("/home/django/lua/message.lua")    -- you should provide complete path of message.lua
print(msg)
like image 32
Prashant Gaur Avatar answered Dec 16 '25 22:12

Prashant Gaur



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!