When needing very fast execution implying lots of Lua and C code, either push all data into C structures and work from there or push all data into Lua to avoid binding and function calls overhead. For example, it would be a bad idea to loop through all the pixels of an image using operator(int i) to implement a filter in Lua. Anatomy of a Lua to C Call; Putting It All Together; Make an msleep Function; We've Just Scratched the Surface; Introduction Earlier you read the Calling Lua From a C Program web page showing how to call Lua from C. There are a lot of instructions with no examples, always leaving something out, so you have to keep trying various things. All C or C functions that will be called from Lua will be called using a pointer of this type: typedef int (.luaCFunction) (luaState.L); In other words, functions must have a Lua interpreter as the only argument and return only an integer. Since a Lua interpreter is used for the argument, the function can actually take any number of.
This first edition was written for Lua 5.0. While still largely relevant for later versions, there are some differences.
The fourth edition targets Lua 5.3 and is available at Amazon and other bookstores.
By buying the book, you also help to support the Lua project.
The fourth edition targets Lua 5.3 and is available at Amazon and other bookstores.
By buying the book, you also help to support the Lua project.
Programming in Lua |
Part IV. The C APIChapter 24. An Overview of the C API |
Lua is an embedded language.That means that Lua is not a stand-alone package,but a library that can be linked with other applicationsso as to incorporate Lua facilities into these applications.
You may be wondering:If Lua is not a stand-alone program,how come we have been using Lua stand alone through the whole book?The solution to this puzzle is the Lua interpreter(the executable
lua
).This interpreter is a tiny application(with less than five hundred lines of code)that uses the Lua library to implement the stand-alone interpreter.This program handles the interface with the user,taking her files and strings to feed them to the Lua library,which does the bulk of the work (such as actually running Lua code).This ability to be used as a library to extend an applicationis what makes Lua an extension language.At the same time, a program that uses Lua can register newfunctions in the Lua environment;such functions are implemented in C (or another language)and can add facilities that cannot bewritten directly in Lua.This is what makes Lua an extensible language.
These two views of Lua(as an extension language and as an extensible language)correspond to two kinds of interaction between C and Lua.In the first kind, C has the control and Lua is the library.The C code in this kind of interactionis what we call application code.In the second kind, Lua has the control and C is the library.Here, the C code is called library code.Both application code and library code usethe same API to communicate with Lua,the so called C API.
The C API is the set of functions that allow C codeto interact with Lua.It comprises functions to read and write Lua global variables,to call Lua functions,to run pieces of Lua code,to register C functions so that they can later be called by Lua code,and so on.(Throughout this text, the term 'function' actually means'function or macro'.The API implements several facilities as macros.)
The C API follows the C modus operandi,which is quite different from Lua.When programming in C,we must care about type checking (and type errors),error recovery, memory-allocation errors,and several other sources of complexity.Most functions in the API do not check the correctness of their arguments;it is your responsibility to make sure that the argumentsare valid before calling a function.If you make mistakes,you can get a 'segmentation fault' error or something similar,instead of a well-behaved error message.Moreover, the API emphasizes flexibility and simplicity,sometimes at the cost of ease of use.Common tasks may involve several API calls.This may be boring,but it gives you full control over all details,such as error handling, buffer sizes, and the like.
As its title says,the goal of this chapter is to give an overview of what isinvolved when you use Lua from C.Do not bother understanding all the details of what is going on now.Later we will fill in the details.Nevertheless,do not forget that you can find more details about specific functionsin the Lua reference manual.Moreover, you can find several examples of the use of the API in theLua distribution itself.The Lua stand-alone interpreter (
lua.c
)provides examples of application code,while the standard libraries (lmathlib.c
, lstrlib.c
, etc.)provide examples of library code.From now on, we are wearing a C programmers' hat.When we talk about 'you', we mean you when programming in C,or you impersonated by the C code you write.
A major component in the communication between Lua and C is anomnipresent virtual stack.Almost all API calls operate on values on this stack.All data exchange from Lua to C and from C to Lua occursthrough this stack.Moreover, you can use the stack to keep intermediateresults too.The stack helps to solve two impedance mismatches between Lua and C:The first is caused by Lua being garbage collected,whereas C requires explicit deallocation;the second results from the shock between dynamic typing in Luaversus the static typing of C.We will discuss the stack in more detail in Section 24.2.
Copyright © 2003–2004 Roberto Ierusalimschy. All rights reserved. |
Using Lua with .Net C# part II
In the previous post I showed how the Lua source code can be built for use by .Net, and how to make a very simple hello Lua script, and execute it from .Net code.
Putting Lua to real use
To actually do something interesting Lua must be able to call into .Net functions that is registered with Lua.
To actually do something interesting Lua must be able to call into .Net functions that is registered with Lua.
Samsung s7 edge frp bypass odin. This enables all sorts of exciting features, such as exposing your business / game objects to Lua and create Lua scripts for AI, custom business processing etc.
.Net function signature for Lua callbacks
Every .Net function that Lua should be able to call must match a specific function signature, and must also be registered with Lua.
Every .Net function that Lua should be able to call must match a specific function signature, and must also be registered with Lua.
This is how the function signature should look in .Net:
Every .Net function exposed to Lua must return an int and takes a pointer to the Lua state as its single argument.
The Lua state object is used to get the parameters for the function along with any other variable values you need for your logic to work.
Communicating with Lua and the Lua stack
You do not operate on the Lua state itself, instead you call Lua C library functions which all takes the Lua state as parameter.
You do not operate on the Lua state itself, instead you call Lua C library functions which all takes the Lua state as parameter.
Lua uses a stack for all communication from .Net to Lua (and from any other language to Lua)If you want to create a new object in Lua (called a Lua table) you use the stack available from the Lua state to create it and set values of any desired fields.
In short, you will need wrapper functions in .Net to operate on the Lua stack, and Lua exports a whole bunch of functions that operates on this stack, which I will show later.
A complete guide for the lua stack can be found in the Lua documentation, section 3 at http://www.lua.org/manual/5.1/manual.html
Lua wrappers and the Lua.h source code file
Lua has an API function for registering a function from another language, its quite simple and when wrapped in .Net I created one that looks like this:
Lua has an API function for registering a function from another language, its quite simple and when wrapped in .Net I created one that looks like this:
Dont worry too much about the m_refs.Add(func); call.
When I first started out creating a Lua wrapper I learned the hard way (debugging debugging debugging) that .Net garbage collects delegates, in use for Lua callbacks, before I intended .Net to do so.
When I first started out creating a Lua wrapper I learned the hard way (debugging debugging debugging) that .Net garbage collects delegates, in use for Lua callbacks, before I intended .Net to do so.
When Lua calls back into .Net, the function pointer is suddenly no more valid, and a runtime exception occurs.
By maintaining a list of references to registered Lua callbacks in .Net, I make sure that the garbage collector wont collect the functions pointers before I want it to. The list Im using in my wrapper is defined as this:
When I close Lua I just empty the list of refs and they will be collected and I will be happy.
The wrapper for the register function looks like this:
The wrapper for the register function looks like this:
You might wonder why theres no DLLImport Attribute.
Take a look at the definition from lua.h, its actually a macro using two other Lua API functions. These two functions must be wrapped as well.
Lua uses macro definitions here and there, actually lua_pushcclosure and lua_setglobal is also just macros:
Take a look at the definition from lua.h, its actually a macro using two other Lua API functions. These two functions must be wrapped as well.
Lua uses macro definitions here and there, actually lua_pushcclosure and lua_setglobal is also just macros:
The lua_pushcclosure and lua_setfield functions is actual C API function and is lua.h defined and wrapped like this:
This is getting a bit boring I hope I did not lose you completely there, if I did Im sorry ?
The point is to show how Lua API functions can be put in a .Net wrapper that emulates the complete Lua API.
The point is to show how Lua API functions can be put in a .Net wrapper that emulates the complete Lua API.
Registering a .Net callback funtion with Lua
Lets imagine that we have created a game and in that game we have created a class in .Net which contains methods for manipulating a “NPC player” object.
Now we want to be able to create combat scripts, task scripts, AI scripts etc.
Lets imagine that we have created a game and in that game we have created a class in .Net which contains methods for manipulating a “NPC player” object.
Now we want to be able to create combat scripts, task scripts, AI scripts etc.
Furthermore we want users of the game to be able to create their own levels and define behaviour for NPC characters in that level.
Most users can learn to write a Lua script and we choose to expose some functionality from the “NPC player” class.
We fire up an instance of Lua by creating a Lua state, and then we register some .Net functions with Lua.
Most users can learn to write a Lua script and we choose to expose some functionality from the “NPC player” class.
We fire up an instance of Lua by creating a Lua state, and then we register some .Net functions with Lua.
Samsung g550fy frp lock umt. Somewhere in our ScriptEngine we have defined:
![Lua Lua](https://www.gdatasoftware.com/fileadmin/web/general/images/blog/2016/07_2016/GDATA_SecurityBlog_wow_script_CHAT_MSG_ADDON_code_anonym.png)
And open Lua:
Our NPCPlayer class definition:
None of our methods match the Lua signature so we have to create Lua ‘trampolines’ for them and handle the Lua communication specifics in them. We register a Lua function callback for the NPCPlayer class like this:
![Code Code](https://i.ytimg.com/vi/kDHGfHxwymI/maxresdefault.jpg)
Calling the registered C# method from Lua
The Lua_InCombat method can now be used in a Lua script, Lua will pass the string parameter on its stack structure.
The Lua_InCombat method can now be used in a Lua script, Lua will pass the string parameter on its stack structure.
The Lua script could look something like this:
characterName = ‘Winnie the pooh’
winnieFighting = InCombat(characterName)
characterName = ‘Winnie the pooh’
winnieFighting = InCombat(characterName)
Its perfectly possible to mess up by calling the Lua function without any parameters or a parameter of a wrong type, there is no type checking, other than the defensive code you can and should implement in your .Net methods.
This concludes the post about registering and using c# methods from Lua.
Hope you found it usefull, please feel free to comment.
Hope you found it usefull, please feel free to comment.
Thue Tuxen
C++ And Lua
Tags: .Net, C#, embedding, integrating, Integration, Lua, Lua C API, Lua source code, Lua.org, register c# function, script, scripting, Thue Tuxen, tuxen consulting