Required documents for Lua: Lua Study Notes

Source: Internet
Author: User

LuaRequired documents:LuaLearning notes are the content to be introduced in this article.LuaSome of the problems encountered and their experiences are suitable for the lack of anyLuaBasic friends. I will sort my study into notes from time to time.LuaIt is also a learning stage.

The ultimate goal of my learning is to apply Lua, maybe some friends aim to apply Lua on the Web -- or something else -- but I think There will always be something in common on the way to the final application. I hope these words will help you.

First, I would like to mention the more common Chinese Reference Documents PIL5.0 Chinese tutorial and Lua user manual 5.1 (Fengyun translation ).

This section aims to build an environment for testing Lua in VS2005. Focus on interaction between C/C ++ and Lua-apply the Lua script to the CPP file.

How to compile a. lua file:

Any text editor works, as long as the written statements comply with the Lua syntax. The suffix is ". lua ". The Lua editor I use is LuaEdit, but I feel that it is no different from notepad except to check whether the syntax is correct...

How to configure the Lua environment:

How to generate the compiled LUA file:

Be sure to solve the above three problems. Do not be impatient until you have successfully configured the use environment and can write simple. do not read the following text until the lua file is generated.

Okay, let's start RTFS (Read The Fuxking Source ).

The following is a Lua script

 
 
  1. --test.lua  
  2. function f ( x, y)  
  3.     return x + y  
  4. end 

Test the LuaEdit syntax.

 
 
  1. // The following is the test. c file
  2. //
  3. // Lua Test Object
  4. // C ++ Source lua_test.cpp
  5. //
  6. //
  7. // Include Files
  8. //
  9. Extern "C"
  10. {
  11.  
  12. # Include "D: \ My Documents \ Visual Studio 2005 \ Projects \ lua. h"
  13. # Include "D: \ My Documents \ Visual Studio 2005 \ Projects \ lua \ lualib. h"
  14. # Include "D: \ My Documents \ Visual Studio 2005 \ Projects \ lua \ lauxlib. h"
  15. }
  16. //
  17. // Libraries
  18. //
  19. # Pragma comment (lib, "D: \ My Documents \ Visual Studio 2005 \ Projects \ lua \ release \ lua. lib ")
  20. //
  21. // Global Variables
  22. //
  23. Lua_State * L;
  24. //
  25. // Lua Functions
  26. //
  27. Double f (double x, double y)
  28. {
  29. Double ret;
  30. Lua_getglobal (L, "f"); // obtain the global variable f
  31. Lua_pushnumber (L, x); // the operand pressure stack.
  32. Lua_pushnumber (L, y); // the operand pressure stack.
  33. Lua_call (L, 2, 1); // execute: 2 operands, 1 return value
  34. // Lua_pcall (L, 2, 1, 0); // The lua_call in protection mode. 0 indicates the error handling code. The specific application is unknown for the time being. It is briefly described in the user manual.
  35. Ret = lua_tonumber (L,-1); // convert the top element of the stack to a number and assign it to ret.
  36. Lua_pop (L, 1); // an element pops up from the stack.
  37. Return ret;
  38. }
  39. //
  40. // Main Functions
  41. //
  42. Int main (void)
  43. {
  44. Int error;
  45. L = lua_open (); // create a Lua interface pointer to borrow DX terminology, essentially a stack pointer)
  46. Luaopen_base (L); // load the basic Lua Library
  47. LuaL_openlibs (L); // load the Lua universal extension Library
  48. Error = luaL_loadfile (L, "test. lua"); // read The Lua source file to the memory.
  49. Double ret = f (10, 3.4); // call the template function f
  50. Printf ("ret = % f", ret); // output result, C language, irrelevant to Lua
  51. Getchar (); // The console program debugging skills to help you observe the results
  52. Lua_close (L); // closes the Lua interface.
  53. Return 1;
  54. }

You can directly copy the code to the. lua and. cpp files, or manually enter the code. I suggest the latter-just like taking notes in class-with a better memory than writing a pen.

Is the compilation successful? If it fails, the environment is not configured properly. However, even if the compilation is successful, it is useless: D. The program will surely jump out when executing the "lua_call (L, 2, 1);" statement in the f () function. If your eyes are fast enough and your English is good enough, you will see the Debug information from Lua within 0.3 seconds: PANIC: unprotected error in call to Lua API (attempt to call a nil value), which is a BUG that I intentionally leave in the program.

Let's see why something went wrong.

When "lua_call (L, 2, 1);" is called, an empty value is called, indicating that the stack is empty. When executing a function in a script, Lua will first press the function body onto the stack and then the operand.

So where does the function body go? The reason is that error = luaL_loadfile (L, "test. lua"); in main.

FirstLuaIt is a "dynamic compilation script language", while loadfile only loads the source file into the memory, but it also lacks the "Compilation" step. You can use "luaL_dofile (L," test. lua ");" to replace. It is both loaded and compiled. After replacement, the execution should be fine.

However, luaL_dofile is actually a macro:

 
 
  1. #define luaL_dofile(L, fn) \  
  2.  (luaL_loadfile(L, fn) || lua_pcall(L, 0, LUA_MULTRET, 0)) 

LUA_MULTRET is also a macro definition. The value is-1, indicating that the function has multiple return values (Lua rule, pil 24.2 -- stack ).

The following two sentences are extended:

 
 
  1. luaL_loadfile(L, fn);  
  2. lua_pcall(L, 0, LUA_MULTRET, 0); 

When the above parameters are executed, pcall will compile the source program loaded into the memory into a binary code that can be used for execution, and stack the global variables to Lua. The function is also a variable, pil 2.5 -- Functions, after all, the function name and function body are two different things ). The. exe/. dll file behind windows 3.1is the same as the "section" file in the pefile format ). Of course, it doesn't matter if you don't know any PE files-I just make an analogy-it's the. obj file generated when VS2005 compiled code.

Although dofile is used directly in 99% of actual use cases, I want to give this question a more intuitive understanding of "dynamic compilation ".

Note that.LuaDefines a template function f and accepts two operands (x, y). Therefore, you need to define the CPP template double f (double x, double y), they must appear in pairs. Otherwise, why should we use Lua: D ). Of course, you can also make the CPP function f accept three parameters x, y, and z, but only apply the pressure stack of y and z, and process x separately, the same principle can also be applied to LUA files. I will not write the source code. You can use it as an exercise.

Finally, let's talk about the luac.exe and. OUT files, which are independent.LUAThe binary file generated by the compiler. Because. LUA is too direct, and the source code can be seen directly. At the same time, dynamic compilation also takes extra time. There may be other reasons. We can find it through further learning), so we use it. the out file is a good solution.

Now, can I directly load the file? Unfortunately, this is not the case! Loadfile is a silly function. It only reads files and determines whether the source file is read or the compiled binary code. The job is done by lua_pcall (). If it is a source file, after compilation, press the stack. If it is binary code, press the stack directly.

Again, if you use the OUT file in the program, the attempt to call a nil value error will still be reported during debugging in VS2005 -- even if you use luaL_dofile ()!

 
 
  1. For example, error = luaL_dofile (L, "luac. out ");

LuaError! The. exe file directly executed by the supervisor is correct. I am not clear about the cause of this problem.

Summary:LuaRequired documents:LuaThe content of the study notes has been introduced. I hope this article will help you!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.