This example downloads
1.c# interaction with Lua Please refer to my previous article Lua combined C # to invoke C + + or C functions
2. In C #, how to put a piece of code fragments in the main thread execution. For WinForm Programs:
public void Executemethodinmainthread ()
{
if (this. InvokeRequired)
{this
. Invoke (New action<action> (Executemethodinmainthread));
return;
}
Fill in the code to be executed on the main thread
For WPF:
public void Executemethodinmainthread ()
{this
. Dispather.invoke (() =>
{
///fill in the code to be executed on the main thread
));
3. In Lua, the specified code fragment is executed in the main thread:
Anonymous functions in A.lua:
Local fun=function () return
5;
End local
result=fun ();--b value is 5
One of the functions of a delegate in b.c# is to use the method as an argument:
public void DoSomething (Action a)
{
A ();
}
public void Delay ()
{
thread.sleep (3000);
}
DoSomething (Delay);
In this way, the function in Lua is also functional, whether it can be passed as a delegate.
The answer is yes.
In C #, declare the following function, and then call in Lua:
Public Form1 ()
{
InitializeComponent ();
Lua = new Nlua.lua ();
Lua[' this '] = this;
Lua. Loadclrpackage ();
}
public void Executemethodinmainthread (Action a)
{
if (this. InvokeRequired)
{this
. Invoke (New action<action> (Executemethodinmainthread), a);
return;
}
A ();
}
Then fill in the Test.lua as follows:
Import ("System.Threading");
function UpdateTime () while
(true) does local
t=os.date ("*t");
Str=t.hour ... ":". T.min ... ":". t.sec;
This:executemethodinmainthread (
function ()
this.label1.text=str;
End
);
Thread.Sleep ();
End
End
updatetime ();
Where Label1 is a label on the main form, set to public or not accessible in Lua.
The last call to the Lua file:
private void Button1_Click (object sender, EventArgs e)
{
new Thread (() =>
{
lua. Dofile ("Test.lua");
Start ();
}
The above implements the purpose of using threads to update the UI in Lua.
This example downloads