- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Passing Lua script from C++ to Lua
The idea of passing Lua script from C++ to Lua includes the fact that we will have to load the libraries and header files as Lua is ANSI C, and if we are coding in C++, we will need to enclose the #includes in extern “C”.
The old and mostly used approach would be to load the libraries that Lua provides and then simply call the C++ function from Lua.
In order to load the script from C++ to Lua, we need to set up and shutdown the Lua interpreter and we can do that with the help of the following code.
Example
Consider the code shown below as −
extern "C" { #include "lua.h" #include "lualib.h" #include "lauxlib.h" } int main(int argc, char *argv[]){ lua_State* L; initialize Lua interpreter L = luaL_newstate(); load Lua base libraries (print / math / etc) luaL_openlibs(L); //////////////////////////////////////////// We can use Lua here ! ///////////////////////////////////////////// lua_close(L); printf( "Press enter to exit..." ); getchar(); return 0; }
And after this we can simply make use of the LuaL_dostring(L, …) function that sends a string straight to the Lua interpreter, and it will be executed just as if that string was in a file that was executed with a dofile.
Example
Consider the code shown below as −
luaL_dostring(L, "for x = 1, 5 do print(x) end");
Output
1 2 3 4 5
- Related Articles
- How to Call a Lua function from C?
- How to Use lua-mongo library in Lua Programming?
- Install Lua in Linux and implement PHP Lua Extension
- How to compile embedded Lua code in C?
- math.min() function in Lua
- string.find() function in Lua
- string.sub() function in Lua
- Comments in Lua Programming
- How to Compile a Lua Executable?
- How to create standalone Lua executables?
- table.pack() function in Lua programming
- table.unpack() function in Lua programming
- Lexical Conventions in Lua Programming
- math.ceil() function in Lua programming
- math.floor() function in Lua programming
