Using Lua as a configuration file instance for a C language project _lua

Source: Internet
Author: User

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

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.