Variable in another module to be used in current module - 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.

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

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)

Functions don't have fields, but tables do. So you can do
ModuleName.FunctionName -- a function in ModuleName
ModuleName.VariableName -- a variable in ModuleName
ModuleName.TableName.FieldName -- a field from a TableName which is in ModuleName
Note FieldName could itself reference a table, and VariableName could be a function, table, string, number, coroutine, etc.

Related

Is it safe to have subroutine with the same name in different fortran modules? [duplicate]

I'm pretty new in the Fortran world. I get a piece of code, where I find difficulty in understanding it.
Let's say in module A, var is declared as a parameter of integer type:
integer, parameter :: var = 81
Then in another module B, an array with the name var is declared:
integer :: var(2)
When these modules are used in a third module C:
use A
use B
Won't there be conflict in the names? Or the two members of the array var will take the value 81?
There will be a compile time error when you attempt to access the variable var in your described case. The specific error will look like:
Error: Name 'var' at (1) is an ambiguous reference to 'var' from module 'a'
Are those variables meant to be globally scoped? You can declare one (or both) of them with private so they are scoped to the module and do not pollute the global scope. In this case though, module C would not be able to use the private variable. Another option is to limit what is imported in your use statement with:
use A, only: some_variable1, some_other_variable
use B, only: var
This would let var from B into the scope of C, and would hide var from A.
If you have to have both variables in module C, you can rename one when you use the module. E.g.:
use A, varA => var
use B, varB => var
which lets you access the variables var in each module by the names varA and varB.
See this example:
module A
integer, parameter :: var = 81
contains
end module
module B
integer :: var(2)
contains
end module
module C
use A, varA => var
use B, varB => var
contains
end module
program test
use C
print *, varA
end program
which will print 81.

Get list of variables in the current namespace in Julia

I have a question that is similar to, but different than this one. I have a function within a module, and I would like to see what variables are defined inside the function namespace. In the other post, they said to use varinfo, but that seems to only work in the Main namespace. For example if I run this
module Test
function hello()
a = 1
varinfo()
return a
end
end
import .Test
Test.hello()
I get this error
WARNING: replacing module Test.
ERROR: UndefVarError: varinfo not defined
Is there a way to get a list of variables within a given namespace? What I am looking for is a function that when called, outputs all the available variables (a in my example) as well as available modules within the namespace.
PS. I would like to add, that varinfo is incredibly limiting because its output is a Markdown.MD, which cannot be iterated over. I would prefer a function that outputs variables and values in some sort of list or dictionary if possible.
varinfo is showing only the global variables.
If you want the local variables, you need to use the Base.#locals macro:
module Test
function hello()
a = 1
println(Base.#locals)
return a
end
end
And now you can do:
julia> Test.hello()
Dict{Symbol, Any}(:a => 1)
1
Is this what you want?
module Test
function hello()
a = 1
println(Main.varinfo(#__MODULE__; all=true, imported=true))
return a
end
end

How to call this method in lua?

So I'm trying to create an arrayList in lua following this module
https://github.com/SnakeSVx/spacebuild/blob/master/lua/includes/modules/arraylist.lua#L26
So first I started with
l = ArrayList:Create()
now I tried to create the list itself
l.list = List:Create()
However that's not the right way to do it. The method goes like this
function list:Create( thetype, isfunc )
self:SetCheckType(thetype, isfunc)
self.table = {}
end
To create an object with that module, use the function documented for creating objects:
local l = ArrayList.Create()
Create is a non-method function in the namespace created by the module ("ArrayList"). It's definition and documentation begin on line 364.
Most of the other functions in module are methods. So, you would pass an instance to them using Lua's method syntax (instance:method(...))
l:Add(item, index)

Lua - How do I dynamically call a module?

Here's some much-simiplified Lua code I'm working with. I need to know how to dynamically call another module ('zebra'):
avar = require "avar"
bvar = require "bvar"
function create(zebra)
print(zebra.new())
end
print(create(avar))
And here are two modules:
local Avar = {}
function Avar.new()
return "avar"
end
return Avar
local Bvar = {}
function Bvar.new()
return "new"
end
function Bvar.old()
return "old"
end
return Bvar
If I try to pass in the string "avar" to my 'create' function, it doesn't work. If I pass in the word 'avar' with no quotes, it does work, however, I don't understand what avar with no quotes is? It seems to be a blank table? Not sure how to pass a blank table as an argument in my main program.
But maybe I'm totally on the wrong path. How do I dynamically call modules?
You can require any time:
function create(zebraModuleName)
zebraType = require(zebraModuleName)
print(zebraType .new())
end
print(create("avar"))
print(create("bvar"))
avar without the quotes is a global variable you created. It is initialized to the value returned by the require function1, which is the value returned by the module you are invoking. In this case, its a table with the new field that happens to be a function.
1 Importing a modules in Lua is done via regular functions instead of a special syntax. The function call parenthesis can be ommited because parens are optional if you write a function call with a single argument and that argument is a string or a table.
Other than that, there are also some other things you are confusing here:
The table you are storing on avar is not empty! You can print its contents by doing for k,v in pairs(avar) do print(k,v) end to see that.
The avar, bvar and create variables are global by default and will be seen by other modules. Most of the time you would rather make them local instead.
local avar = -- ...
local bvar = -- ...
local function create (zebra)
-- ...
end
The create function clearly expects a table since it does table indexing on its argument (getting the new key and calling it). The string doesn't have a "new" key so it won't work.
You aren't really dynamically calling a module. You are requiring that module in a regular way and it just happens that you pass the module return value into a function.
create always returns nil so there is no point in doing print(create(avar)). You probablu want to modify create to return its object instead of printing it.
You can use standard require from lua language or build your own loader using metatables/metamethods.
1. create a global function:
function dynrequire (module)
return setmetatable ({},{
__index = function (table,key)
return require(module..'.'..key)
end
})
end
2. Create your project tree visible to package.path
./MySwiss/
\___ init.lua
\___ cut.lua
\___ glue.lua
\___ dosomething.lua
3. Make your module dynamic
you only need to put this line on your MySwiss/init.lua (as if you were namespacing a PHP class):
return dynrequire('MySwiss')
4. Require your module and use subproperties dynamically
On your script you only need to require MySwiss, and the folder file (or subfolders with dynrequire('MySwiss.SubFolderName').
var X = require('MySwiss')
X.glue()
Note that MySwiss doesn't have glue key. But when you try access de glue key the metamethod __index try to require submodule. You can the full project tree using this technique. The only downside is the external dependencies not packed this way.

Lua callback into module

My script registers itself for a callback using
require "cmodule"
index = 1
cmodule.RegisterSoftButtonDownCallback(index, "callbackFunc")
where callbackFunc is the name (a string) of the callback function. Now I turned this script into a module, but the callback is not called anymore, I assume because the callback function is not in the scope of the cmodule. How can I solve this? (Lua newbie)
cmodule is a device driver that has Lua bindings.
Edit: My complete solution based in the answer from BMitch below:
require "cmodule"
local modname = "myModule"
local M = {}
_G[modname] = M
package.loaded[modname] = M
local cmodule = cmodule
local _G = _G
setfenv(1,M)
function callbackFunc()
-- use module vars here
end
_G["myModule_callbackFunc"] = callbackFunc
index = 1
cmodule.RegisterSoftButtonDownCallback(index, "myModule_callbackFunc")
You need to have something defined in the global space for a string to be evaluated back to a function call.
Depending on how they implemented RegisterSoftButtonDownCallback, you may be stuck defining the function itself, rather than the table/field combination like myModule.callbackFunc. To minimize the namespace pollution, if you can't use myModule.callbackFunc, then I'd suggest myModule_callbackFunc=myModule.callbackFunc or something similar. So your code would look like:
require "cmodule"
index = 1
myModule_callbackFunc=myModule.callbackFunc
cmodule.RegisterSoftButtonDownCallback(index, "myModule_callbackFunc")
For a better fix, I would work with the cmodule developers to get their program to accept a function pointer rather than a string. Then your code would look like:
require "cmodule"
index = 1
cmodule.RegisterSoftButtonDownCallback(index, myModule.callbackFunc)