Forward function parameter arg in lua - function

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

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)

How to pass an object as argument to an anonymous function in MATLAB?

I'm working on a MATLAB app that programatically creates anonymous functions to evaluate any native MATLAB function and pass it a list of variables as argument. In the example below, 'formula' contains a string with the function and arguments to be evaluated (e.g., "sum( var1, var2 )" ). The formulas sometimes contain function calls nested within function calls, so the code below would be used recursively until obtaining the final result:
Func2 = str2func( sprintf( '#(%s) %s', strjoin( varNames, ',' ), formula ) );
This evaluates fine for native MATLAB functions. But there's a particular case of a function (named Func1) I made myself that not only needs the list of variables but also an object as argument, like this:
function output = Func1( anObject, varNames )
% do some stuff with the object and the vars
end
For this particular function, I've tried doing this:
Func2 = str2func( sprintf( '#(%s,%s) %s', "objectToPassToFunc1", strjoin( varNames, ',' ), "Func1(objectToPass,""" + strjoin( varNames, '","' ) +""")" ) )
...which doesn't throw an error, but Func1 doesn't receive the objectToPassToFunc1, instead it gets values from one of the variables in varNames. And I don't know why.
So how can I correctly pass the object to Func1????
Matlab doesn't care about the type of arguments you pass to a function. As a matter of fact, the input could be scalar, vector, matrix, and even an object of a class. See the following example.
classdef ClassA
methods
function print(~)
disp('method print() is called.');
end
end
end
This class has only one method. Now, let us define an anonymous function func which accepts one input.
func = #(arg) arg.print;
Notice that we explicitly assume that the input is an object of ClassA. If you pass another type of data to this function, Matlab will throw an error. To test the code,
obj = ClassA;
func = #(arg) arg.print;
func(obj)
To avoid the error, you may need to check the type of the input before using it. For example,
function [] = func(arg)
% check if arg is an object of ClassA
if isa(arg,'ClassA')
arg.print;
end
end
Now you can pass different types for the input without getting an error.

Assigning function to Global Variable in Lua

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

Julia - Change method definition within a function

So here's what I want, I have a function: f(x,t)=... where x is the "true" variable and t is a parameter. However, I need to use this function as a parameter in the Calculus package's derivative. This function requires a function with only one parameter. For this what I thought off was to redefine a method f(x)=f(x,t) where I fix the t parameter before passing it to the derivative function. This has to be done within another function.
However, doing this literally returns this error :
syntax: cannot add method to function argument f
I believe due to variable scope issues you should simply select a different name for your new function. You can also use anonymous functions instead of named definitions.
function foo(t_val)
newf(x) = f(x, t_val)
derivative(newf, otherparams...)
end
With anonymous functions,
function foo(t_val)
derivative(x -> f(x, t_val), otherparams...)
end
You can also assign anonymous functions to variables and use the variables as a function.
function foo(t_val)
newf = x -> f(x, t_val)
derivative(newf, otherparams...)
end

Calling the function name

As a beginner in Lua, I am sorry if the answer on this is easy.
I was trying to call a function within a code, yet after 2 hours of searching I couldn't find the wanted results. (Maybe I use the wrong search query's?)
Example code
function Test123 ()
SayTest = True
if SayTest = True then
-- This Is where I want to call the function name Test123,
-- yet I can't seem to succeed in this since it is just
-- starting a new function
SystemNotice ( role, function)
end
end
This should be the result:
function Test123 ()
SayTest = True
if SayTest = True then
SystemNotice ( role, 'Test123')
end
end
If anyone can help me out, I would be thankful. If I am still being unclear, just tell me and I will try to describe it better. My excuses for my limited English.
In Lua functions are actually values. That means they do not really have a name, you can only assign them to a variable or table field, but since the value itself has no concept of its name, you can't retrieve it.
That said, with the debug library, you can do this:
function getfname()
return debug.traceback("", 2):match("in function '(.-)'");
end
function bar()
print(getfname())
end
bar(); -- prints bar
foo = bar;
foo() -- prints foo
knerf = {rab = bar};
knerf.rab() -- prints rab
Note that this only works with the default Lua error handler or one that returns the same or very similar output, however you can obviously modify the pattern to suit what you need.
Read this: I would not advise this solution for performance-intensive tasks. Both string matching and the traceback are not really suited for this. Also, obviously the debug library must be enabled so you can actually use the traceback function.
Your function declaration lacks anend.
function Test123 ()
end
Read the functions chapter from the Lua manual. Just for the record, your if will also need an end.
This is a construct that just goes against the Lua philosophy that functions are first class citizens:
a function is just another value, and as such it has no name.
A variable can be assigned a value, thus binding a function to a name.
But that name can change. or a function can have multiple names. Which one to pick?
A better solution would be creating an anonymous function with an upvalue (a closure) instead:
function genTest(name)
return function()
SayTest = true
if SayTest == true then
print ( 'role', name)
end
end
end
Test123 = genTest('Test123')
Test123()
foobar = Test123
foobar()
This creates a function with a bound local variable name (see PiL 6.1 ).