How to call a function from other script in LUA? - function

I have a root folder named "root".
In this folder I have 2 more directories, each with one folder, each with a script:
/root/script01/client_script01/main.lua
In this script I have this:
local function OpenWindow()
stuff
end
And
/root/script02/client_script02/main.lua
I want to use OpenWindow() function in second script!

You are correct that you can call OpenWindowfrom client_script02/main.lua if you do not use the local keyword in the definition.
This however is not best practice. I am unsure of the specifics of your environment or intent, but in most cases it is better to create a lua module and use the require function to load it.
This is better because it shows the relationship between the files, showing that client_script02/main.lua requires client_script01/main.lua to be loaded to operate properly.
Your module could look something like this:
local client_script01 = {}
client_script01.OpenWindow = function()
--stuff
end
return client_script01
The other script something like this:
local cs01 = require('client_script01')
do
cs01.OpenWindow()
--stuff
end
You would also need to adjust your file structures to better suit this convention, based on how the require function preforms searching: lua-users - Package Path

Related

List Lua functions in a file

How can I list all the functions included in a Lua source file?
For example, I have fn.lua which contains
function test1()
print("Test 1")
end
function test2()
print("Test 2")
end
And I wish to be able to display those function names (test1, test2) from another Lua script.
The only way I can figure at the moment is to include the file using require, then list the functions in _G - but that will include all the standard Lua functions as well.
Of course I could just parse the file manually using the string search functions, but that doesn't seem very Lua to me!
This will eventually form part of a process that allows the developer to write functions in Lua, and the operator to select which of those functions are called from a list in Excel (yuk!).
If you put them all in a "module" (which you should probably do, anyway):
mymodule = { }
function mymodule.test1()
print("Test 1")
end
function module.test2()
print("Test 2")
end
return mymodule
It becomes trivial:
mymodule = require"mymodule"
for fname,obj in pairs(mymodule) do
if type(obj) == "function" then
print(fname)
end
end
If you absolutely have to keep them in raw form, you'd have to load them in a different way to separate your global environment, and then iterate over it in a similar way (over the inner env's cleaned _G, perhaps).
I see three ways:
Save the names in _G before loading your script and compare to the names left in _G after loading it. I've seen some code for this, either in the Lua mailing list or in the wiki, but I can't find a link right now.
Report the globals used in a function by parsing luac listings, as in http://lua-users.org/lists/lua-l/2012-12/msg00397.html.
Use my bytecode inspector lbci from within Lua, which contains an example that reports globals.
If you want to do this, it's better to define the function is a package, as described in Programming in Lua book:
functions = {}
function functions.test1() print('foo') end
function functions.test2() print('bar') end
return functions
Then you can simply iterate your table functions.

Call a function that is not on the Matlab path WITHOUT ADDING THAT PATH

I have been searching an entire afternoon and have found no solution to call in matlab a function by specifying its path and not adding its directory to the path.
This question is quite similar to Is it possible to call a function that is not in the path in MATLAB?, but in my case, I do not want to call a built-in function, but just a normal function as defined in an m-file.
I think handles might be a solution (because apparently they can refer to functions not on the path), but I again found no way to create a handle without cd-ing to the directory, creating it there and the cd-ing back. Trying to 'explore' what a function handle object is and how to make one with a reference to a specific function not on the path has led me nowhere.
So the solution might come from two angles:
1) You know how to create a handle for an m-file in a specific directory.
2) You know a way to call a function not on the matlab path.
EDIT: I have just discovered the function functions(myhandle) which actually lets you see the filepath to which the handle is referring. But still no way to modify it though...
This is doable, but requires a bit of parsing, and a call to evalin.
I added (many years ago!) a function to the MATLAB Central File Exchange called externalFcn
http://www.mathworks.com/matlabcentral/fileexchange/4361-externalfcn
that manages calls to off-path functions. For instance, I have a function called offpathFcn that simply returns a structure with a success message, and the value of an input. Storing that function off my MATLAB path, I can call it using:
externalfcn('out = C:\MFILES_OffPath\offpathFcn(''this is a test'')');
This returns:
out =
success: 1
input: 'this is a test'
(Note that my implementation is limited, and improvable; you have to include an output with an equal sign for this to work. But it should show you how to achieve what you want.)
(MathWorks application engineer)
The solution as noted in the comment 1 to create a function handle before calling the function is nicely implemented by #Rody Oldenhuis' FEX Contribution:
http://www.mathworks.com/matlabcentral/fileexchange/45941-constructor-for-functionhandles
function [varargout]=funeval(fun,varargin)
% INPUT:
% fun: (char) full path to function file
curdir=cd;
[fundir,funname]=fileparts(fun);
cd(fundir);
[varargout{1:nargout}] =feval(funname,varargin{:})
cd(curdir);
I've modified Thierry Dalon's code to avoid the use of feval, which I always feel uncomfortable with. Note this still doesn't get around cd-ing to the directory in question, but well, it happens behind the scenes, so pretend it doesn't happen :-)
Also note what Ben Voigt pointed out above: calls to helper functions off the path will fail.
function [varargout]=funeval(FunctionHandle, FunctionPath, varargin)
% INPUT:
% FunctionHandle: handle to the function to be called; eg #MyFunction
% FunctionPath: the path to that function
% varargin: the arguments to be passed to Myfunction
curdir=cd;
cd(FunctionPath)
[varargout{1:nargout}] = FunctionHandle(varargin{:});
cd(curdir);
end
and calling it would look like
Output = funeval(#MyFunction, 'c:\SomeDirOffMatlabsPath\', InputArgToMyFunc)
The run command can run a script file from any directory, but it can't call a function (with input and output arguments).
Neither feval nor str2func permit directory information in the function string.
I suggest writing your own wrapper for str2func that:
saves the working directory
changes directory to the script directory
creates a function handle
restores the original working directory
Beware, however, that a handle to a function not in the path is likely to break, because the function will be unable to invoke any helper code stored in other files in its directory.

Global function in lua

Is there a way to have a function in Lua that can be accessed from any module in a project without having to first require it?
something like:
module(..., package.seeall);
function globFoo()
print('global foo called');
end
and have it called from somwhere else, like main
--main
globFoo();
without requiring it?
A module is just a Lua script. You can do whatever you want there; you don't even have to call module in your module script. Indeed, module is generally considered harmful these days, which is why it was deprecated in Lua 5.2.
Really, it's a matter of simply moving your code around:
function globFoo()
print('global foo called');
end
module(..., package.seeall); --Module created after global function
So yes, you can have a module modify the global table. I would very much suggest that you don't (because it creates implicit ordering between Lua scripts, which makes it hard to know which script uses which stuff). But you can do it.
A sample of how this is done :
in global.lua (where the global function is located) :
globalFunction1 = function(params)
print("I am globalFunction1")
end
In the calling file, caller.lua :
globalFunction1(params) -- This will call the global function above

How do I define custom function to be called from IPython's prompts?

I had an old ipy_user_conf.py in which I included a simple function into the user namespace like this:
import IPython.ipapi
ip = IPython.ipapi.get()
def myfunc():
...
ip.user_ns['myfunc'] = myfunc
Then, I could use myfunc in the prompt.
However, I updated to IPython 0.12.1 and now the ip_user_conf.py does not work. I haven't seen how to translate such a custom function for prompts to the new configuration model.
Which is the way to do this?
Best regards,
Manuel.
UPDATE: Changed the subject to question
After reading a bit of the documentation (and peeking at the source code for leads) I found the solution for this problem.
Simply now you should move all your custom functions to a module inside your .ipython directory. Since what I was doing was a simple function that returns the git branch and status for the current directory, I created a file called gitprompt.py and then I included the filename in the exec_file configuration option:
c.InteractiveShellApp.exec_files = [b'gitprompt.py']
All definitions in such files are placed into the user namespace. So now I can use it inside my prompt:
# Input prompt. '\#' will be transformed to the prompt number
c.PromptManager.in_template = br'{color.Green}\# {color.LightBlue}~\u{color.Green}:\w{color.LightBlue} {git_branch_and_st} \$\n>>> '
# Continuation prompt.
c.PromptManager.in2_template = br'... '
Notice that in order for the function to behave as such (i.e called each time the prompt is printed) you need to use the IPython.core.prompts.LazyEvaluation class. You may use it as a decorator for your function. The gitprompt.py has being placed in the public domain as the gist: https://gist.github.com/2719419

Accessing the Body of a Function with Lua

I'm going back to the basics here but in Lua, you can define a table like so:
myTable = {}
myTable [1] = 12
Printing the table reference itself brings back a pointer to it. To access its elements you need to specify an index (i.e. exactly like you would an array)
print(myTable ) --prints pointer
print(myTable[1]) --prints 12
Now functions are a different story. You can define and print a function like so:
myFunc = function() local x = 14 end --Defined function
print(myFunc) --Printed pointer to function
Is there a way to access the body of a defined function. I am trying to put together a small code visualizer and would like to 'seed' a given function with special functions/variables to allow a visualizer to 'hook' itself into the code, I would need to be able to redefine the function either from a variable or a string.
There is no way to get access to body source code of given function in plain Lua. Source code is thrown away after compilation to byte-code.
Note BTW that function may be defined in run-time with loadstring-like facility.
Partial solutions are possible — depending on what you actually want to achieve.
You may get source code position from the debug library — if debug library is enabled and debug symbols are not stripped from the bytecode. After that you may load actual source file and extract code from there.
You may decorate functions you're interested in manually with required metadata. Note that functions in Lua are valid table keys, so you may create a function-to-metadata table. You would want to make this table weak-keyed, so it would not prevent functions from being collected by GC.
If you would need a solution for analyzing Lua code, take a look at Metalua.
Check out Lua Introspective Facilities in the debugging library.
The main introspective function in the
debug library is the debug.getinfo
function. Its first parameter may be a
function or a stack level. When you
call debug.getinfo(foo) for some
function foo, you get a table with
some data about that function. The
table may have the following fields:
The field you would want is func I think.
Using the debug library is your only bet. Using that, you can get either the string (if the function is defined in a chunk that was loaded with 'loadstring') or the name of the file in which the function was defined; together with the line-numbers at which the function definition starts and ends. See the documentation.
Here at my current job we have patched Lua so that it even gives you the column numbers for the start and end of the function, so you can get the function source using that. The patch is not very difficult to reproduce, but I don't think I'll be allowed to post it here :-(
You could accomplish this by creating an environment for each function (see setfenv) and using global (versus local) variables. Variables created in the function would then appear in the environment table after the function is executed.
env = {}
myFunc = function() x = 14 end
setfenv(myFunc, env)
myFunc()
print(myFunc) -- prints pointer
print(env.x) -- prints 14
Alternatively, you could make use of the Debug Library:
> myFunc = function() local x = 14 ; debug.debug() end
> myFunc()
> lua_debug> _, x = debug.getlocal(3, 1)
> lua_debug> print(x) -- prints 14
It would probably be more useful to you to retrieve the local variables with a hook function instead of explicitly entering debug mode (i.e. adding the debug.debug() call)
There is also a Debug Interface in the Lua C API.