How can i call lua function that takes self as a parameter from C? - c

For example, If I have function like
foo = function(self) print ("Foo") end
to call this function, I would say, foo:()
How do I call this kind of function from C?

foo:() is not legal.
That function would need to be in a table for the : call syntax to work.
tab = {
foo = function(self)
print "Foo"
end
}
tab:foo()
The important thing to know is that tab:foo() is just syntactic sugar for tab.foo(tab) (only tab is only evaluated once).
So to call that manually you just need to pass the object as the first argument yourself.

Related

Parentheses in .sorted(by: ) method

I have an array for example:
let myArray = [12,123,412,412,4,124,32]
And i want it sorted in ascending way, i create a function for it
func sortedAscending(_ i: Int , _ j: Int) -> Bool{ return i < j }
Then i create variable for storing new sorted array
let newSorted = myArray.sorted(by : sortedAscending())
Right here compiler gives me error like: error: argument passed to call that takes no arguments
When i delete parentheses it works fine. Can anyone explain why i should call a function sortedAscending without parentheses?
The reason is because when you pass sortedAscending without parentheses, you are passing the closure itself as a parameter. This is what you want to do, in fact, because you are telling sorted(by:) to use the passed-in closure to do its sorting.
By contrast, if you add the parentheses to sortedAscending(), you are telling the compiler to execute the closure first, and then pass the result of that to sorted(by:). If sortedAscending() returns another closure that takes two Ints, this can work, but in your case, sortedAscending() just returns a Bool, and sorted(by:) can't take a Bool as an argument. In addition, the attempt to call sortedAscending() fails, because it requires two Int parameters, and you didn't provide any.
The error message, of course, is completely misleading, making it sound like the error is something totally different from what it actually is, because Swift.
The sorted(by:) function expects a closure as the argument. By adding the parentheses after sortedAscending, you are actually trying to call the sortedAscending function (with no parameters) and pass the return value of the sortedAscending function as the argument to sorted(by:).
By eliminating the parentheses, you properly pass the function as the closure argument.
But you don't need a function. Just do:
let newSorted = myArray.sorted { $0 < $1 }

Why doesn't this assignment work outside of a function?

Here's an example of what I have going on. This first piece of code will not work.
typedef struct {
char *desc;
unsigned quantity;
} item;
item *inventory[INVENTORY_SIZE];
item thing = { "This is a thing.", 2 };
inventory[0] = &thing; // Fail.
int main(void){
// Code goes here.
}
The following code will work, however.
typedef struct {
char *desc;
unsigned quantity;
} item;
item *inventory[INVENTORY_SIZE];
item thing = { "This is a thing.", 2 };
int main(void){
inventory[0] = &thing; // Works.
}
I know I can't call functions outside of a function but that I can assign globals outside of a function. This looks like an assignment. So then why doesn't it work?
EDIT: As soon as I clicked 'post', I think I realised the answer. You can assign values in a declaration outside of a function, but only if it's a declaration. That's the answer, isn't it?
When we write :
data_type variableName = someValue;
It means we are first declaring variableName to be a variable, and of the type data_type. Subsequently, an assignment of a value is being done, immediately afterwards and since this is the first value assigned to variableName, it's also initialising it to someValue.
Which is allowed. This is a special type of function, a system function, known as initialisation.
But writing
variableName = someValue;
means we are attempting to assign someValue to variableName outside the scope of any function, and outside the scope of an initialisation.
This is not possible outside a function.
Code only executes from within called functions, with the exception of initialisation, which occurs during an initial assignment.
This should work, if it what you're trying to accomplish:
item thing = { "This is a thing.", 2 };
item *inventory[INVENTORY_SIZE] = {&thing};
These are definitions (since they are at top level scope), so the compiler will go ahead and allocate storage for them in this translation unit.
item thing = { "This is a thing.", 2 };
is not an assignment despite what it may look like. It's actually an initialisation (part of a declaration) which is perfectly valid outside of a function.
On the other hand,
inventory[0] = &thing;
is an assignment which has to be inside a function of some description.
Bottom line, you should not apply initialisation rules to assignments.
Youre guess is right: the second example is initialisation, rather than execution of the statement. It's legal because global variables are created before the execution of the program (i.e., initial call to main function). Think of it like that: the command flow starts in the main function and it goes into all function that is called from it as they are called in the program's code. So at any moment the program is within some function, and any commands (besides initializations which are done beforehand) that do not lie within some function are automatically dead code --- the program has no means to reach them.
First of all,
item thing = { "This is a thing.", 2 }
is an initialization, which is a special case, not an assignment. This sets the initial value of a variable. Initialization is bonded with declaration, so it can reside in a file scope.
The assignment expression can only reside inside a function. To put it in simple words, an assignment needs to be executed at run-time, so if it is not inside a function scope, there is no way to know when to execute it.

How do I pass a class as an argument to a function in UnrealScript?

I want to do
result = TraceActors(class'QuadForcePawn', HitEnemy, hitLocation, HitNorm, weaponStart, m_oldWeaponStartLocation[iHand], vExtent);
but I want to substitute a variable for the class'QuadForcePawn' part. I haven't been able to figure out how to do this.
This is so I can have a function that calls TraceActors, and that function takes an argument telling it which kinds of Actors to look for.
Technically, TraceActors is actually an iterator function and is meant to be used with the foreach keyword, so you wouldn't actually assign the result to a variable.
To answer your question, what you want to use is a class reference variable. An example function might look like this (TraceActors actually requires many more parameters, but I've left them out for brevity.):
function TraceFor (class<Actor> traceClass)
{
local Actor A;
foreach TraceActors(traceClass, A)
{
// do work here
}
}
Class reference variables are declared with the class keyword, and optionally you can use the <> syntax to limit the classes which can be assigned to it. class<Actor> declares a class reference variable which can only have Actor or subclasses of Actor assigned to it. In the example function above, a call to TraceFor(class'Pawn') would work fine, but a call to TraceFor(class'Object') would fail to compile.
If you want to return the result of the TraceActors call, one way to do it might be to build an array of the results and return that:
// Returns an array of Actors of the passed in type.
function TraceFor (class<Actor> traceClass, out array<Actor> results)
{
local Actor A;
foreach TraceActors(traceClass, A)
{
results.AddItem(A);
}
}

Passign code as a function parameter instead of declaring a callback

I think that some newer languages like JS can do this natively, but I forget the term for it (make a "temporary" function in-line just to pass as a callback)
What I want to do is ...
I'm writing unit tests where I set up expected input & output messages at compile time. Later at run time, I want to do some checks when each output is received or input has been processed, so I added a parameter for a callback function.
That's working fine and I could leave it & move on, but ... I am just curious ...
sometimes a function is overkill and I just need a single comparison; sometime a small block of code would do. Perhaps I could just evaluate these to a zero/non-zero value at run time? But how to pass as a parameter?
At the moment my function has the following signature
void AddExpectedCommand(E_peripheralType peripheral,
communicationBlock_t commandBlock,
errorMessage_t errorMessage,
void *(*DoRunTimeChecks)(E_boolean));
where the final parameter is pointer to a callback function returning boolean.
Is there any way that I could pass a code expression as a parameter instead?
Or does a function seem "cleaner"?
Thanks in advance for any help ...
Update: oops, I got my declaration wrong. I want to pass a pointer so a function which has no parameters and returns an e_Boolean ... how do I do that?
With C++11 you can do the following:
Function taking a function that returns a bool:
void f(function<bool()>);
Call it with a lambda capturing a local variable:
int x = ...;
f([&x]() { return (x > 2); });
Or call it with some function g that returns a bool:
bool g();
f(g);
Or bind some function h that takes an int and returns a bool:
bool h(int x);
f(bind(h, 2)); // ie creates a nullary function from h(2)
What you're looking for is called a "lambda expression" or "anonymous function." And they don't exist in C (but do in C++ with certain qualifications).

Difficulties translating Matlab to C

I have some Matlab functions that I have to translate in C but I do not understand the syntax or the behaviour to create.
I have this call and the following implementation:
{
...
[vSolution,sReturnVal] = Func1(10, #(X) Func2(X, hour_of_the_day));
...
}
function [SolutionVector,ReturnValue] = Func1(IterationsTermination, FuncToUse)
function [ReturnValue] = Func2(TestedSolution, shour_of_day)
I thought that the '#(x)' was there to define an anonymous function possessing an X parameter (a simple pointer to function), but is here used with a named function with parameters, and the X value define within the parameter list.
How can I understand it and translate it in C?
It is defining an anonymous function. But that anonymous function happens to call Func2. The anonymous function is equivalent to:
function Y = myFunc(X)
Y = Func2(X, hour_of_the_day);

Resources