Imagine a scene: your C program needs to have a window that you want users to be able to customize the window size. There are many methods, such as using environment variables, or files with key-value pairs. Anyway, you need to parse it. Using the LUA configuration file is a good choice.
First, you can define the following configuration file:
Copy Code code as follows:
--define window Size
width = 100
Height = 50
We then write a function to parse it and use the Lua API to guide the LUA parsing configuration. , the following is the complete program:
Copy Code code as follows:
#include <stdio.h>
#include <string.h>
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
Void Load (lua_state* l, const char* fname, int *w, int *h)
{
if (Lual_loadfile (L, Fnam e) | | Lua_pcall (l, 0, 0, 0)) {
error (L, "error:%s", lua_tostring ( L,-1));
}
Lua_getglobal (L, "width");
Lua_getglobal (L, "height");
if (!lua_isnumber (L,-2)) {
Error (L, "width shuld be num.");
}
if (!lua_isnumber (L,-1)) {
Error (L, "Height shuld be num");
}
*w = Lua_tointeger (L,-2);
*h = Lua_tointeger (L,-1);
}
int main ()
{
Lua_state *l = Lual_newstate ();
Lual_openlibs (L);
int W, H;
Load (L, "config", &w, &h);
printf ("%d,%d", W, h);
return 0;
}
What are the benefits of using the LUA profile? I think there are probably the following reasons:
1.Lua handles all grammatical details for you (including errors)
2. The configuration content is readable so that you can even write notes.
3. It is easy to add new configuration information.
Finish