Assigning function to Global Variable in Lua - function

This is the sample test code.
s="\\command{sample execution}"
u=string.gsub(s,"\\(%b{})",print)
It works fine as print is global function. I defined function myprint as follows.
myprint = function(x,y)
return print(x,y)
end
Now the command u=string.gsub(s,"\\(%b{})",myprint) does not work. This is because the myprint is not global variable as the print is. So basic question that I want to ask is "How to assign function to global variable in Lua?"

You just need to write:
global_function_1 = function (arg)
-- body
end
or use the syntactic sugar alternative:
function global_function_2 (arg)
-- body
end
Make sure that the part in which you do that doesn't have a local variable with selected name. For instance none of the following functions are global:
local bar
local function foo (arg)
local zee
function arg () end
zee = function () end
function bar () end
end
Please note that I have totally ignored assigning to table members and ignored existence of _G and _ENV, and let's leave it this way.
I think that it is worth mentioning that the string.gsub (or really any function call) doesn't care whenever the function (or any argument) is local or whatever:
local str = "abc"
local function fn (x) print(x) end
string.gsub(str, "%a", fn)
outputs:
a
b
c

Related

Retrieving A Function From A WebhookScript Global Variable

In WebhookScript, I can store a function in a variable with:
sub = function(a, b) {
return a - b
}
I'd like to store a function in a Global Variable so that I can use it in multiple Custom Actions. But if I've saved the above function as $sub$ then
sub2 = var('$sub$')
subX = sub(1,2)
causes an error:
Trying to invoke a non-function 'string' # line...
And
function subX(a,b){
var('$sub$')
}
when sub only contains return a - b, doesn't work either.
Obviously I need to convert the string to a function but I'm not sure whether that's possible.
I know this is a bit of an obscure language but if anyone knows how this can be done in similar languages like JavaScript and PHP, I'm happy to test out any guesses...
The solution here is to remove the function section and just enter the script, which inherits the execution scope so if my global variable $script$ is:
return 'hello ' + a
Then I can execute the function with:
a = 'world'
value = exec(var('$script$'))
echo(value)
(credit to Webhook.Site's support team for explaining this)

In Julia, why can "if false" statements in local scope modify function definitions?

In Julia 1.4.1, if I define a function in a global scope, modifications after "if false" statements do not affect it, as expected:
test()=0
if false
test()=1
end
println(test())
This prints "0", as it should. However, when I enclose this code within a local scope, the behavior changes:
function main()
test()=0
if false
test()=1
end
println(test())
end
main()
This now prints "1" which I did not expect. If I change "test" to be an array or a float I observe no modification as expected, i.e. the problem does not occur. Why does Julia behave this way for functions?
The solution is to use anonymous functions in cases like this:
function main()
test = () -> 0
if false
test = () -> 1
end
println(test())
end
julia> main()
0
As for the why, this gets to the core of what it means to define and redefine a particular method of a function.

What Meaning Of This Function

function [TC]=Translate(T0,Base)
end
I know that Translate is a function and T0 and Base his parameter but what is [TC]?
Octave (and matlab) have a rather unique way of returning variables from functions. Instead of defining explicitly what to return from the function using a return keyword, they define from the outset which variables will be returned when the function exits, and octave simply looks for those variables by name at the time the function exits, and returns their values, whatever they may be by that point.
Your function may return nothing:
function returnsNothing();
disp('hello, I return nothing');
end
or it may return one output:
function Out = returnsOne(x)
Out = x+5
disp('This function will return the value of Out');
end
or it may return more than one outputs:
function [Out1, Out2] = returnsTwo(x)
Out1 = x+5;
Out2 = x+10;
end
You would call the last function from the octave terminal (or script) like this:
[a,b] = returnsTwo(5); % this will make a = 10 and b = 15

Forward function parameter arg in lua

I would like to override a function to inspect its parameter values but the call it and pass the original parameters as normal. Is this possible? I am using Corona SDK by www.coronalabs.com
My code at present, which does not work, is:
-- getting a refrence to the original function so i can replace it with my overriding function
local newcircle = display.newCircle
-- my override
display.newCircle = function(...)
-- attempt to pass the parameters to this function on to the real function
local t = {...}
newcircle(unpack(t))
end
-- calling the overridden function as if it were normal
display.newCircle( display.newGroup(), "image.png" )
In your new display.newCircle implementation, you are using the undefined t table, and the deprecated arg automatic table.
Try this :
-- my override
display.newCircle = function(...)
local t = {...} -- you need to collect arguments to a table
-- dumb use of override
print(t[1])
-- attempt to pass the parameters to this function on to the real function
newcircle(unpack(t))
end

Lua - find out calling function

In Lua, is it possible to know which function has called the current function.
For instance
function a()
get_calling_function() --Should print function b
end
function b()
a()
end
Is something like this possible?
Does the debug library have such functionality?
You could use debug.traceback():
function a()
print(debug.traceback())
end
function b()
a()
end
b()
which would print:
stack traceback:
./test.lua:45: in function 'a'
./test.lua:50: in function 'b'
./test.lua:53: in main chunk
[C]: in ?
you can use debug.sethook() to set up a hook that gets called each time certain special events happen in lua. it can be useful for things like this.
local debugInfo = { caller = nil, callee = nil }
function hook()
local info = debug.getinfo(2)
if info == nil then
debugInfo.callee = nil
return
end
-- we only want to watch lua function calls (not C functions)
if info.what ~= "Lua" then
debugInfo.callee = "C function"
return
end
debugInfo.caller = debugInfo.callee
debugInfo.callee = info.name
end
debug.sethook(hook, "c")
function caller1()
if debugInfo.caller ~= nil and debugInfo.callee ~= nil then
msg = debugInfo.callee.. " was called by ".. debugInfo.caller.. "!"
print(msg)
end
end
function caller2()
caller1()
end
caller2()
this prints 'caller1 was called from caller2!'
debug.sethook can handle 3 different characters in the second parameter so you can let it know when to notify you. 'c' means call your hook function any time a function is called in lua, 'r' means call your hook function every time a function returns in lua, and 'l' means call your hook function whenever lua processes a new line of code.
you could set this up to build your own custom stack trace if you really wanted to, and you could also use debug.getlocal() within your hook to even try to work out what arguments were passed to your called function.
edit for lhf. this is actually a much simpler way of doing what you're asking, if you don't need to track this and just need to know the context of how the function was called.
function caller1()
local current_func = debug.getinfo(1)
local calling_func = debug.getinfo(2)
print(current_func.name.. " was called by ".. calling_func.name.. "!")
end
function caller2()
caller1()
end