How do you pass an object from c# to lua's function? - c#

I'm using Lua interface on c# to pass an object I created to lua's function.
It successfully calls the function, but lua is keep throwing an error:
LuaInterface.LuaException: /hook.lua:32: attempt to index local 'objj' (a nil value)
This is the c# code:
public class PerObj
{
public string name;
public PerObj()
{
}
}
PerObj obj = new PerObj();
LuaFunction lf = lua.GetFunction ("item.HookMe");
lf.Call(obj);
And here's the lua code:
function item:HookMe(objj)
objj.name= "lalala"
end
The function is actually being called, but I'm not sure it's not working...

Change the function definition to:
function item.HookMe(objj)
objj.name= "lalala"
end
The colon in the original definition means that the function has also the self parameter. Those function are called like this: object:HookMe(). But you want to call it directly, so the colon is not applicable.
Edit:
If you want to keep the function defininition and retain self, call it like this:
lf.Call(null, obj);
To call it passing also the self object:
lf.Call(lua["item"], obj);

It seems like the problem is the design of the Lua method (but it really depends on the intent):
Instead of
function item:HookMe(objj)
-- self not used
objj.name= "lalala"
end
This would work better in the given example:
function item:HookMe()
self.name= "lalala"
end
The reason (as well discussed in other answers) is that declaring a function with the method syntax (:) adds an implied first formal parameter self. The caller can pass anything as the first actual argument but the contract is usually to pass the parent table of the function so it can access its sibling fields.
In this case, name seems to be a sibling of HookMe so the method shouldn't be operating on an arbitrary table passed as objj but instead on self.

Related

C# pass a method as a parameter without specifying a method signature

My goal is to be able to pass in a a method as a parameter just like a call back in javascript, But without specifying it's return value, or its function signature.
For example in javascript I could do:
function test(fn()){
fn();
}
fn() in JavaScript can be interpreted to any function type:
function [return value] test(){}
function [void] test(){}
function [...] (arg1,arg2...){}
(function arguments overloading is possible...)
C# isn't offering me much with "Action" and "Func".
In C# I can create a delegate and then specify which type of a delegate it is:
Action: a delegate to a function that returns void, all functions that the Action will point to, have to contain the same exact signature (not cool...)
Func: a delegate to a function that returns a value, all functions that the Func will point to, have to contain the same exact signature (not cool...)
Using an Object will bring me to an expensive boxing/unboxing story, which I would like to avoid.
C# experts, talk to me..
You call it "not cool", I call it "type safe"....
One solution might be the way you call the method. When this is the method you want to call:
public void Test(Action fn)
{
fn();
}
And this is the one you want to pass:
public string MethodWithReturnType()
{
return "Hello World!";
}
Then you can call Test with MethodWithReturnType by using a lambda:
Test(() => MethodWithReturnType());
Your only real option is object function(object[]){} but as you say there are huge issues with interpreting the object actual type. C# is a strongly typed language unlike javascript and so the capabilities that you want are just not possible, and if they are then they shouldn't be used because you'll lose all of the advantages of using a strongly typed language in the first place.

What does it mean when a C# function parameter contains `= null`?

I'm going through an MVC tutorial and see this line of code at the beginning of a function:
private void PopulateDepartmentsDropDownList(object selectedDepartment = null)
After testing it out, I can see that the function works, but I do not understand how the function parameter works. What does object selectedDepartment = null do?
I have done a general internet search and have not yet been able to locate an answer.
I guess my question really has two facets:
What does the = null portion of the parameter do?
Is it something that can be done but not necessarily should be done?
It means that that parameter will be null, unless you decide to pass something. So in other words, its optional.
It can be done, and there is nothing wrong with it. Its pretty common practice.
It means that you can call
PopulateDepartmentsDropDownList()
or
PopulateDepartmentsDropDownList("something")
both because compiler will convert the first one to
PopulateDepartmentsDropDownList(null)
This feature is called Optional Arguments
I suggest you to read this blog post
the = null is the default value of the parameter, it is the functional equivalent as if you had
private void PopulateDepartmentsDropDownList()
{
PopulateDepartmentsDropDownList(null);
}
private void PopulateDepartmentsDropDownList(object selectedDepartment)
{
//Your code here.
}
So if you can call the function with no parameters PopulateDepartmentsDropDownList() it will call the 1 perameter version and pass in null.
This sets the argument to a default value (if not provided) and prevents a compile time error if the argument is not provided. See:
Setting the default value of a C# Optional Parameter
Basically this argument is now optional so you can call the function in either of these two ways:
PopulateDepartmentsDropDownList() //selectedDepartment will be set to null as it is not provided
OR
PopulateDepartmentsDropDownList(myObject) //selectedDepartment will become myObject

In C#, can I send an out parameter to be used elsewhere

I have a function that is getting called by another part of the code, with the signature:
public override bool DoSomething(Foo f, out string failed)
{
failed = "I failed";
_anotherClassMethodExpectingString.SetString(failed);
}
So my question is - If i need to send the other class method the same string that my caller is expecting back in its "out" parameter, can i just send it the same variable, without having any effect on my caller? The "out" parameter is a little confusing to me .. Should I have used something like this instead:
public override bool DoSomething(Foo f, out string failed)
{
string localStr = "I failed";
failed = localStr;
_anotherClassMethodExpectingString.SetString(localStr);
}
Unless the subsequent method you're calling is also using an out parameter then there's no need to define a local variable. The string will be unaffected by any regular parameter passing.
If you do not expect or do not desire for your method's caller to see any alteration from the third method, what you have is fine. If I am reading your question correctly, this seems to be your intent.
If you wanted your caller to reflect changes introduced by the third method, it would need to be an out parameter there as well, or instead return the modification via a return value which you would then assign to your original out parameter prior to returning.
If a parameter is declared for a method without ref or out, the parameter can have a value associated with it. That value can be changed in the method, but the changed value will not be retained when control passes back to the calling procedure.
Given that strings are immutable in .NET, it is safe to pass failed to any method without ref and out on the string parameter and be sure it won't be changed.
The out parameter is like pointer of the object in c++. So if you don't use 'out' definer ,doesn't change value of the parameter.

Get the name of the parameter that is passed to function [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
get name of a variable or parameter
I have this function.
public void AddVariable( String str)
{
Response.Write(str); // will write the value of str
}
But I need to write the name of the string variable that is passed into the function.
For example:
String temp = "test Variable";
AddVariable(temp);
Here I need to get the name of the variable inside my function, Instead of value.
ie, I need to get 'temp' inside my function, Instead of 'test Variable'.
Is it possbile?
You could get the name of the variable inside the function ("str"), but you cannot get the name of the variable that was passed into the function unless you pass it in as a second parameter.
It doesn't make sense to get the name of the variable passed to the function because there may not have even been a variable if a literal was passed such as AddVariable("test variable").
You don't need parameter name (possible from reflection) but rather a variable name that has been passed as a parameter. AFAIK, for all practical purpose, this is not possible for the code within the function.
On the other hand, it's as such possible to do the code analysis of all assemblies loaded in the app-domain and find all invocations to your method and then do the stack-walk to determine possible invocation so that you may able to nail the variable name in the calling method (again if there can be many invocations in calling method, making it difficult to guess the variable name and you have to then rely on IL offset etc) but its just too convoluted.
Perhaps, you can state the reason for such requirements, there can be some alternative. For example, you can get and log stack trace within your method code that can be used for say trouble-shooting.

Implementation of `Class` like `String` Class

I want to implement class i.e. we have String class in .Net. In that, if you check when we code....
C#:
String strString = "Value-12346- .";
String[] strArray = strString.Substring(0, strString.Length - 1).TrimEnd().ToUpper().Split("-".ToCharArray());
in this example if you check we are calling multiple functions of String Class, over each function i.e over Substring function TrimEnd is called and over TrimEnd Split function is called. I would like to implement similar. Please help me out.
Many Thanks!!!
Make sure every method returns an object of the same type (or the type you want) and then you can call the methods on the object like that ( cascade or chain). Each of the above method in the string example returns a new string ( note that strings are immutable here ), so you can apply the string functions again and so on.
On a related note, see how Fluent Interface works. The C# example showing non-fluent and fluent API is a good example: http://en.wikipedia.org/wiki/Fluent_interface
public IConfigurationFluent SetColor(string newColor)
{
this.color = newColor;
return this;
}
As manojlds pointed out above, you achieve that by making your class' member methods return the type of their owner class. Now, in particular, the String's methods return a new string instance every time (instead of "modifying" the source and returning it), so you might want in your methods to create a deep copy of "this" and then made any changes to the new object and return it. Not only that, but the String class is immutable.
Sorry for being too detailed.

Categories

Resources