In the same way we can have
nullableClassInstance?.method(blah)
Is there a way to do
nullableFunctionInstance?(blah)
In other words, is there an operator that checks whether a function instance is not null, if so, invoke the function all in one line?
Using the call method, you can achieve what you want with:
nullableFunctionInstance?.call(blah)
There's also the apply method if you want to pass arguments.
If you have a Function Object , you can use the call method and send all the parameters to that which works exactly as calling the function. Here , you can use the null aware member access operator.
void myFun(int a , int b){...}
var myVar = myFun ;
call
The function myVar will only get called if its not null as shown below.
myVar?.call( arg1 , arg2 );
apply
If your function is dynamic or you wish to control which function is being called at run time , you can use the apply static method of Function like so :
Function.apply(myVar , [arg1 , arg2]);
apply takes the function and a List of parameters that will be sent to the function.
Read more about call and apply :
Related
I'm trying to change the behavior of a Lua function, by adding code to the start or end of it. Because this is a mod for a game, I can't edit the function directly, so I have to override it instead. I accomplish this by storing a reference to the original function in a local variable, then redefining the function with my own, which calls the original one along with any prefix or postfix code I need to add, like so:
local base_exampleFunction = ExampleBaseGameClass.exampleFunction
function ExampleBaseGameClass.exampleFunction(param1, param2)
--Prefix code goes here
base_exampleFunction(param1, param2);
--Postfix code goes here
end
This works fine for functions defined with the ClassName.functionName syntax, but some functions use ClassName:functionName instead, which from what I understand, are functions that pass a reference to the class instance as the first parameter. I can't figure out how to prefix/postfix these functions, as I get the following error when declaring a variable to hold the original function if I try the same approach:
attempted index: exampleFunction of non-table: null
Is there a way to make this work?
: functions are just scary ways of saying "the first argument is self".
So, ExampleBaseGameClass:exampleFunction(param2) is equivelent to ExampleBaseGameClass:exampleFunction(ExampleBaseGameClass, param2)! It's just got self at the beginning, and functions declared with : will have an invisible self variable appear out of nowhere.
local a = {}
function a.b(self)
print(self)
end
function a:c()
print(self)
end
-- a.c(a) == a:c()
-- a:b() == a.b(a)
-- a:b() == a:c()
Using this idea, we can simply prepend an argument (it does not have to be called "self", it just has to be the first argument).
This should work, unless there is a part of your Lua environment (eg, funky metatables) which would prevent such a thing:
local base_exampleFunction = ExampleBaseGameClass.exampleFunction
function ExampleBaseGameClass.exampleFunction(self, param1, param2)
--Prefix code goes here
base_exampleFunction(self, param1, param2);
--Postfix code goes here
end
The lua library takes advantage of the first argument being the calling object for it's string library. Notice how ("hello"):gsub() works--by passing the string itself as the first argument!
I'm trying to do script for game which replaces avalible function with created function. So this is my LUA code:
function ifEmotePlayed(playerName, emoteID)
if emoteID == 0 then
print(playerName.." is dancing!")
end
end
return
function eventEmotePlayed(playerName, emoteID)
end
Exactly thing i want to do is to replace eventEmotePlayed function with ifEmotePlayed function likely
function ifEmotePlayed(playerName, emoteID)
if emoteID==0 then
print(playerName.." is dancing!")
end
end
Instead of
function eventEmotePlayed(playerName, emoteID)
if emoteID==0 then
print(playerName.." is dancing!")
end
end
Does anyone know how to do it?
If you want to rename a function you simply do it like that:
myNewFunctionName = originalFunctionName
Then calling myNewFunctionName() will be identical to calling originalFunctionName() as myNewFunctionName now refers to the same function as originalFunctionName.
In Lua functions are variables.
You could also define a function that calls the original function and pass the parameters like:
function myNewFunction(a,b)
return originalFunction(a,b)
end
But this is obviously not as efficient as you have to do one additional function call.
If you want to replace a function with your own function so the original function will not be executed but yours instead you simply assign your function to the original functions "name" (actually you make the variable that referred to the original function from now on refer to your own function)
function originalFunction(a,b)
return a + b
end
function myOwnFunction(a,b)
return a * b
end
originalFunction = myOwnFunction
Now originalFunction refers to your function and calling originalFunction(a,b) will return the product of a and b instead of the sum. It's the same as in the first example, just the other way around.
right now iam trying to create some Stored Procedures for a HSQL-DB.
I want to create a new User and return the ID of the new User.
For example i tried it like this to create the Procedure.
create procedure test(out param int)
modifies sql data
begin atomic
set param = 1;
end;
=> Call it
declare param int ;
call test(param);
call param;
=> Error
dynamic parameter or variable required as INOUT or OUT argument
I canĀ“t find the bug -.-
so long.
This is how you call the procedure:
declare param int;
call test(param)
call param
It looks the same, but each statement is executed separately!
What is the syntax to create the function, but then add it's implementation further down in code?
So roughly like this:
Define function doX
Call doX (further down in the code)
doX implemention (i.e. all functions down at the bottom of the file)
You only need to have a variable to reference. local funcName is sufficient for your purposes with one caveat. This will work:
local funcName
function callIt()
print(funcName())
end
function defineIt()
funcName = function() return "My Function" end
end
defineIt()
callIt()
As long as you define it (defineIt) before you call it (callIt), it should work as expected. You can't do something like this though (and this is the caveat):
local funcName
print(funcName())
funcName = function() return "My Function" end
You will get an error: attempt to call local 'funcName' (a nil value).
oh...so there's really no way to call funcName prior to having actually defined the function then? i.e. you still need to make sure defineIt is called before your first call to funcName itself?
I wanted to clarify this point, and I felt that an answer would be the better way than a comment.
Lua is a much simpler language than C or C++. It is built on some simple foundations, with some syntactic sugar to make parts of it easier to swallow.
There is no such thing as a "function definition" in Lua. Functions are first-class objects. They are values in Lua, just like the number 28 or the string literal "foo" are values. A "function definition" simply sets a value (namely, the function) into a variable. Variables can contain any kind of value, including a function value.
All a "function call" is is taking the value from a variable and attempting to call it. If that value is a function, then the function gets called with the given parameters. If that value is not a function (or a table/userdata with a __call metamethod), then you get a runtime error.
You can no more call a function that hasn't been set in a variable yet than you can do this:
local number = nil
local addition = number + 5
number = 20
And expect addition to have 25 in it. That's not going to happen. And thus, for the same reason, you can't do this:
local func = nil
func(50)
func = function() ... end
As Paul pointed out, you can call a function from within another function you define. But you cannot execute the function that calls it until you've filled in that variable with what it needs to contain.
As others have written, you cannot call a function at runtime that has not been assigned prior to the call. You have to understand that:
function myFunc() print('Something') end
Is just a syntax sugar for this:
myFunc = function() print('Something') end
Now, it makes sense that this kind of code would not work the way you want it to:
print(greeter(io.read())) -- attempt to call global 'greeter' (a nil value)
function greeter(name) return 'Hello '..name end
When you use the greeter variable, its value is nil, because its value is set only on the next line.
But if you want to have your "main" program on the top and the functions at the bottom, there is simple way to achieve this: create a "main" function and call it as the last thing on the bottom. By the time the function is called, all the functions will be set to the corresponding global variables:
-- start of program, your main code at the top of source code
function main()
local name = readName()
local message = greeter(name)
print(message)
end
-- define the functions below main, but main is not called yet,
-- so there will be no errors
function readName() io.write('Your name? '); return io.read() end
function greeter(name) return 'Hello, ' .. name end
-- call main here, all the functions have been assigned,
-- so this will run without any problems
main()
I have a lua "animation variable" which has a callback function used in an animation loop.
local av = AnimationVariable(ticker.Position.Y)
...
av:addCallback( ** animation function goes here **)
Skipping over details, this addCallback function is defined as follows in C++:
void LuaUIAnimationVariable::addCallback(luabind::object callback);
and when the animation variable is updated, the callback is executed as such (we call the function with one argument):
luabind::call_function<void>(boost::ref(callback), newValue);
My question is the following: How can I use a member function with addCallback? Assuming I have a Ticker:animate(ypos) function, using addCallback on a Ticker instance addCallBack(ticker:animate) does not compile, and addCallBack(ticker.animate) does not work. I understand that member functions in lua have an implicit "self" first parameter.
Any solution or am I forced to use a global function?
Not sure if I understand your question, but if you mean a Lua member function, you can use a closure:
av:addCallback(function(yval) ticker:animate(yval) end)