Lua C# Integration
Unzip the downloaded file into an arbitrary folder. This will create a single sub-folder named ulua which contains the ULua distribution. Ulua ├── lua.cmd # LuaJIT executable for Windows. ├── lua # LuaJIT executable for OSX and Linux. ├── host │ ├── config.lua # Global configuration (see PKG). │ ├── init # Initialization scripts folder. IUP is a multi-platform toolkit for building graphical user interfaces. It offers a simple API in three basic languages: C, Lua and LED. IUP's purpose is to allow a program source code to be compiled in different systems without any modification.
What is Lua?Lua is a powerful, efficient, lightweight, embeddable scripting language.It supportsprocedural programming,object-oriented programming,functional programming,data-driven programming, anddata description. Lua combines simple procedural syntax withpowerful data description constructs based onassociative arrays and extensible semantics.Luais dynamically typed,runs by interpreting bytecode with a register-based virtual machine,and has automatic memory management with incremental garbage collection,making it ideal forconfiguration,scripting,andrapid prototyping. Where does Lua come from?Lua is designed, implemented, and maintained byateamatPUC-Rio,the Pontifical Catholic University of Rio de Janeiro in Brazil.Lua was born and raised inTecgraf,formerly the Computer Graphics Technology Group of PUC-Rio.Lua is now housed atLabLua,a laboratory of theDepartment of Computer Scienceof PUC-Rio. What's in a name?'Lua'(pronounced LOO-ah)means 'Moon' in Portuguese.As such, it is neither an acronym nor an abbreviation, but a noun.More specifically,'Lua' is a name,the name of the Earth's moon and the name of the language.Like most names,it should be written in lower case with an initial capital, that is, 'Lua'.Please do not write it as 'LUA',which is both ugly and confusing,because then it becomes an acronymwithdifferent meaningsfor different people.So, please, write 'Lua' right! Joining the communityThere are severalmeeting placesfor the Luacommunitywhere you can go to learn and help others andcontributein other ways.One of the focal points is themailing list,which is veryactiveand friendly. You canmeet part of the Lua community in person by attendingaLua Workshop. Supporting LuaYou can help tosupport the Lua projectbybuying a bookpublished by Lua.organd bymaking a donation. You can also help to spread the word about Lua by buying Lua productsatZazzle. | Why choose Lua?Lua is a proven, robust languageLua has been used inmany industrial applications(e.g.,Adobe's Photoshop Lightroom),with an emphasis on embedded systems(e.g.,theGingamiddleware for digital TV in Brazil)andgames(e.g.,World of Warcraft and Angry Birds).Lua is currentlythe leading scripting language in games.Lua has a solidreference manualand there areseveral books about it.Severalversionsof Lua have been released and used inreal applicationssince its creation in 1993.Lua featured inHOPL III,the Third ACM SIGPLAN History of Programming Languages Conference,in 2007.Lua won theFront Line Award 2011from theGame Developers Magazine. Lua is fastLua has a deserved reputation for performance.To claim to be 'as fast as Lua' is an aspiration of other scripting languages.Several benchmarks show Lua as the fastest languagein the realm of interpreted scripting languages.Lua is fast not only in fine-tuned benchmark programs,but in real life too.Substantial fractions of large applications have been written in Lua. If you need even more speed, tryLuaJIT,an independent implementation of Lua using a just-in-time compiler. Lua is portableLua is distributed in a small package andbuilds out-of-the-boxin all platforms that have a standard C compiler.Lua runs on all flavors of Unix and Windows,on mobile devices(running Android, iOS, BREW, Symbian, Windows Phone),on embedded microprocessors (such as ARM and Rabbit,for applications like Lego MindStorms),on IBM mainframes, etc. For specific reasons why Lua is a good choice also for constrained devices,readthis summaryby Mike Pall.See also apostercreated by Timm Müller. Lua is embeddableLua is a fast language engine with small footprint thatyou can embed easily into your application.Lua has a simple and well documented APIthat allows strong integration with code written in other languages.It is easy to extend Lua with libraries written in other languages.It is also easy to extend programs written in other languages with Lua.Lua has been used to extend programs written not only in C and C++,but also in Java, C#, Smalltalk, Fortran, Ada, Erlang,and even in other scripting languages,such as Perl and Ruby. Lua is powerful (but simple)A fundamental concept in the design of Lua is toprovide meta-mechanisms for implementing features,instead of providing a host of features directly in the language.For example,although Lua is not a pure object-oriented language,it does provide meta-mechanisms for implementing classes and inheritance.Lua's meta-mechanisms bring an economy of concepts and keep the language small,while allowing the semantics to be extended in unconventional ways. Lua is smallAdding Lua to an application does not bloat it.Thetarball for Lua 5.4.3,which contains source code and documentation,takes 350K compressed and 1.3M uncompressed.The source contains around 29000 lines of C.Under 64-bit Linux,the Lua interpreter built with all standard Lua libraries takes 278Kand the Lua library takes 466K. Lua is freeLua is free open-source software,distributed under avery liberal license(the well-known MIT license).It may be used for any purpose, including commercial purposes,at absolutely no cost.Justdownloadit and use it. |
Last update:Wed May 19 10:37:28 UTC 2021
In this short tutorial I'll show how to run Lua programs from C and C++ and howto expose functions to them. It's easy!
Update: The code in this post has been updated for Lua 5.2.4. I haven'tchecked if the Lua 5.3 C API is backwards-compatible with 5.2. All the codehere is available on GitHub.
The first program will just create a Lua state object and exit. It will be ahybrid between C and C++. Since the two languages must include different files,we need to discern between them by checking for the existence of the__cplusplus
macro.
Notice that I'm being explicit about which version of Lua I'm using in thecode. If you trust that the Lua developers care about compatibility, you canjust #include <lua.hpp>
and so on directly.
The purpose of the program is just to make sure that we can compile, link andrun it without errors.
You need to let the compiler know where it can find the include files and theLua shared library. The include files are usually located in/usr/local/include
and the library files in /usr/local/lib
. Search yoursystem directories if needed. To compile the above program, pass thedirectories with -I
and -L
, respectively.
You may swap out g++
with llvm-g++
, or just c++
, depending on yourcompiler. If you're using a C compiler, use gcc
or llvm-gcc
— butremember to rename the file to first.c
.
Now try to run the program to make sure it doesn't segfault:
This one worked just fine.
Executing Lua programs from a host
The next step is to execute Lua programs from your C or C++ code. We'll createthe Lua state object as above, load a file from disk and execute it.
Put this into runlua.cpp
or runlua.c
:
You can reuse the compilation arguments from above:
or
Lua C# Integration Example
Running Lua programs
Let's test this with some Lua programs. The first one prints the Lua versionand exits.
You may want to double-check that it works by running lua hello.lua
. It maynot be important for this trivial program, but can become important when youtry more advanced ones.
Now try it with runlua
:
You can even run bytecode-compiled programs:
We should also check that the error handling works. Put some garbage in a filecalled error.lua
, for example
Running it produces
Calling C functions from Lua
It gets very interesting when Lua programs call back to your C or C++functions. We'll create a function called howdy
that prints its inputarguments and returns the integer 123.
To be on the safe side, we'll declare C linkage for the function in the C++version of the program. This has to do with name mangling,but in this case, it really doesn't matter: Lua just receives a pointer to afunction, and that's that. But if you start using dynamic loading of sharedlibraries through dlopen
and dlsym
, this will be an issue. So let's do itcorrect from the start.
Copy the above program into a file called callback.cpp
and add the howdy
function.
We have to pass the address of this function to Lua along with a name. Put thefollowing line somewhere between the call to lua_newstate
andluaL_loadfile
:
Lua C# Integration Tutorial
Create a test program called callback.lua
Compile and test it
I told you it was easy!
Lua C# Integration Code
What next?
Read the Lua C APIReference. You've learned enough now to get going with it. Did you see mynote about clearing the stack in howdy
? You may want to investigate that.
Find out how to integrate Lua closures with your C functions.
If you want to hide or catch console output from Lua, you need to figure thatout as well. I once did it by trapping io.write()
; I copied its code fromlualib.c
and changed io_write
to point to my own function. There isprobably a better way to do it, though. Doing so is useful for things like gameprogramming.
Use RAIIor smart pointers to manage resources like lua_State
.
I also strongly recommend to try out LuaJIT.Calling into your functions there is even easier, using LuaJIT's foreignfunction library. I'll write a blog post on how todo that as well. In short, just create ordinary C functions, compile as ashared library, copy their signatures into pure Lua source code and hook themup with LuaJIT's FFIlibrary.
Lua C Integration
LuaJIT runs between 10-20 and up to 135 times faster than interpreted Lua, soit's definitely worth it.