File: lua1.cpp

package info (click to toggle)
dosbox-x 2025.12.01%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 53,224 kB
  • sloc: cpp: 339,768; ansic: 165,257; sh: 1,455; makefile: 963; perl: 385; python: 106; asm: 57
file content (93 lines) | stat: -rw-r--r-- 1,834 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#include <stdio.h>
#include <string.h>
#include <assert.h>

extern "C" {
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
}

#include <iostream>
#include <fstream>

using namespace std;

int reg_c_function1(lua_State *LUA) {
    (void)LUA;

    printf("* * From C++ here: LUA called reg_c_function1\n");
    return 0;
}

int reg_c_function2(lua_State *LUA) {
    (void)LUA;

    printf("* * From C++ here: LUA called reg_c_function2 '%s'\n",lua_tostring(LUA, -1));
    return 0;
}

int reg_c_function3(lua_State *LUA) {
    (void)LUA;

    printf("* * From C++ here: LUA called reg_c_function3\n");

    lua_pushstring(LUA, "Hello world I am a return value");
    return 1;
}

int main(int argc,char **argv) {
    ifstream i;

    if (argc > 1)
        i.open(argv[1],ios_base::in);
    else
        i.open("lua1.lua",ios_base::in);

    if (!i.is_open()) return 1;

    lua_State *LUA = luaL_newstate();
    assert(LUA != NULL);

    luaL_openlibs(LUA);

    lua_register(LUA, "reg_c_function1", reg_c_function1);
    lua_register(LUA, "reg_c_function2", reg_c_function2);
    lua_register(LUA, "reg_c_function3", reg_c_function3);

    int luaerr;
    char *blob;
    off_t sz;

    sz = 65536;
    blob = new char[sz]; /* or throw a C++ exception on fail */

    i.read(blob,sz-1);
    {
        streamsize rd = i.gcount();
        assert(rd < sz);
        blob[rd] = 0;
    }

    luaerr = luaL_loadstring(LUA, blob);
    if (luaerr) {
        fprintf(stderr,"LUA error: %s\n", lua_tostring(LUA, -1));
        lua_pop(LUA, 1);
        return 1;
    }

    delete[] blob;

    if (luaerr == 0) luaerr = lua_pcall(LUA, 0, 0, 0);

    if (luaerr) {
        fprintf(stderr,"LUA error: %s\n", lua_tostring(LUA, -1));
        lua_pop(LUA, 1);
    }

    assert(LUA != NULL);
    lua_close(LUA);
    i.close();
    return 0;
}