Lua callback into module - 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)

Related

How should I access other modules within a module?

I'm struggling with the "global" aspect of functions as it relates to modules. Maybe someone here could tell me if this example would work, explain why and then tell me the right way to do it.
If I have two modules:
f1.lua
local mod = T{}
function mod.print_msg(msg)
print(msg)
end
return mod
f2.lua
local mod = T{}
function mod.print_hello()
msgmod.print_msg('Hello')
end
return mod
and both are called in a "main" file
msgmod = assert(loadfile(file_path .. 'f1.lua'))()
himod = assert(loadfile(file_path .. 'f2.lua'))()
himod.print_hello()
Would print_hello still work if called from f2 or would I need to loadfile() f1.lua in f2?
It would work if called after the msgmod = ... has been executed (in any file), but not before. This is a confusing situation due to the usage of globals.
Typically, you do not want to use globals like this in modules. You should handle dependencies using require just as you would #include them in C++. So, f2.lua, which wants to use print_msg defined in f1.lua, might look like this:
local f1 = require('f1')
local mod = T{}
function mod.print_hello()
f1.print_msg('Hello')
end
return mod
You should also use require in your main file (and get in the habit of making everything local):
local msgmod = require('f1')
local himod = require('f2')
himod.print_hello()
Note that we could have omitted the first line, since we aren't actually using f1 in main, and f2 will require it automatically when we require f2. Unlike loadfile, require automatically caches loaded modules such that they are loaded only once. Again, require is almost always what you want to use.
The general pattern for writing modules is to require all dependency modules into locals, then use them as you like to implement your module functions:
local dep1 = require('dep1')
local dep2 = require('dep2')
...
local mod = {}
function mod.foo ()
return dep1.bar(dep2.bazz())
end
return mod

unable to use imported modules in event_handler lua

I'm writting a basic event handler in lua which uses some code located in another module
require "caves"
script.on_event({defines.events.on_player_dropped_item}, function(e)
caves.init_layer(game)
player = game.players[e.player_index]
caves.move_down(player)
end
)
but whenever the event is triggered i get following error
attempt to index global 'caves' (a nil value)
why is this and how do i solve it?
You open up the module in question and see what it exports (which global variables are assigned and which locals are returned in the bottom of the file). Or pester the mod author to create interface.
Lua require(filename) only looks up a file filename.lua and runs it, which stands for module initialization. If anything is returned by running the file, it is assigned into lua's (not-so) hidden table (might as well say, a cache of the require function), if nothing is returned but there was no errors, the boolean true is assigned to that table to indicate that filename.lua has already been loaded before. The same true is returned to the variable to the left of equals in the caves = require('caves').
Anything else is left up to author's conscience.
If inside the module file functions are written like this (two variants shown):
init_layer = function(game)
%do smth
end
function move_down(player)
%do smth
end
then after call to require these functions are in your global environment, overwriting your variables with same names.
If they are like this:
local init_layer = function(game)
%do smth
end
local function move_down(player)
%do smth
end
then you won't get them from outside.
Your code expects that the module is written as:
caves = {
init_layer = function(game)
%do smth
end
}
caves.move_down=function(player)
%do smth
end
This is the old way of doing modules, it is currently moved away, but not forbidden. Many massive libraries like torch still use it because you'd end up assigning them to the same named globals anyway.
Кирилл's answer is relevant to newer style:
local caves={
%same as above
}
%same as above
return caves
We here cannot know more about this. The rest is up to you, lua scripts are de-facto open-source anyways.
Addendum: The event_handler is not part of lua language, it is something provided by your host program in which lua is embedded and the corresponding tag is redundant.
You should consult your software documentation on what script.on_event does in this particular case it is likely does not matter, but in general the function that takes another function as argument can dump it to string and then try to load it and run in the different environment without the upvalues and globals that the latter may reference.
require() does not create global table automatically, it returns module value to where you call this function. To access module via global variable, you should assign it manually:
local caves = require "caves"

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.
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.

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.

Can a constructor access the name of the variable its object is being store to?

I want the following code to set the 'name' field of the myClass instance to be equal to 'super_awesome_name':
super_awesome_name = myClass();
where the myClass constructor is as follows:
function obj = myClass()
obj.name = ???;
end
Is there some way to do this in Matlab? Right now I can accomplish something very similar with assignin, but it makes the syntax very unnatural:
myClass(super_awesome_name);
where the myClass constructor is as follows:
function obj = myClass(var_name)
obj.name = assignin('caller',var_name, obj);
end
As far as I know, there is no convenient way of doing so. You can see this yourself since MATLAB will have to perform some when constructing an object like that.
First construct the object
Store that object in super_awesome_name
But step 1 needs information from step 2 (i.e. the name of the variable). So you will have to work around that.
You solution may work, but it leaves a lot of room for error. Just consider the case when super_awesome_name is undefined before the construction: this will throw an exception due to an unitialized variable.
IMHO it is easier to make a constructor that accepts a string containing the name (or possibly a variable, as you can get the variable name of an argument by using inputname). Using inputname, however is just a bit clearer than using assignin.
Why do you need such functionality? I'm thinking of a situation where you might do something like:
x = myObjectThatHasAName(); % x.name contains 'x'
y = myObjectThatHasAName(); % y.name contains 'y'
x = y; % x.name contains 'y' !
So that might be the behavior you are looking for, but it may become very confusing if you pass the variables along a lot. It looks to me like you are mixing debugging information into your actual computations.
If you need the functionality to determine the actual variable name in another method or function, just use inputname. Then you won't need to keep track of the variable name yourself with all confusing consequences. That would be what I'd propose to do in most cases. You can see an example in the MATLAB documentation.
On the other hand, I think the clearest way to store the variable name inside the object, could be something like:
classdef myObjectThatHasAName
properties
name = '';
end
methods
function obj = myObjectThatHasAName()
end
function obj = storeName(obj,name)
if nargin < 2
name = inputname(1);
end
if ~isempty(name) % && isempty(obj.name)
obj.name = inputname(1);
end
end
end
end
I haven't tested this (lack of MATLAB on my current computer), but the following code should do it:
x = myObjectThatHasAName();
x = x.storeName();
% or x = storeName(x);
% or x = storeName(x,'x');
If you don't mind the overhead, you could always incorporate the storeName into each other method (and forget about calling storeMethod outside of the methods). This keeps track of the variable name where the object resided before the last assignment. A possible method might look like this:
function obj = otherMethod(obj,arguments)
obj = obj.storeName(inputname(1));
% actual code for the method
end
That way the name is set when you first call any method on the object (this almost does what you want, but I guess it will do what you need in most cases). You can of course adjust the code to just remember the first assignment (just comment out the code in storeName).