File: hslauxlib.c

package info (click to toggle)
haskell-lua 2.3.3%2Bds1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 276 kB
  • sloc: haskell: 1,582; ansic: 403; makefile: 7
file content (76 lines) | stat: -rw-r--r-- 1,647 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
#include <HsFFI.h>
#include <lua.h>
#include <lauxlib.h>
#include "hslauxlib.h"
#include "hslcall.h"

/* Auxiliary Library */

/*
** Creates a new Lua state and set extra registry values for error
** bookkeeping.
*/
lua_State *hsluaL_newstate()
{
  lua_State *L = luaL_newstate();

  /* add error value */
  lua_createtable(L, 0, 0);
  lua_setfield(L, LUA_REGISTRYINDEX, HSLUA_ERR);

  /* register HaskellFunction userdata metatable */
  hslua_registerhsfunmetatable(L);

  return L;
}


/*
** Helper for hsluaL_tostring
*/
static int hsluaL__tolstring(lua_State *L)
{
  luaL_tolstring(L, 1, NULL);
  return 1;
}

/*
** Converts object to string, respecting any metamethods; returns NULL
** if an error occurs.
*/
const char *hsluaL_tolstring(lua_State *L, int index, size_t *len)
{
  lua_pushvalue(L, index);
  lua_pushcfunction(L, hsluaL__tolstring);
  lua_insert(L, -2);
  int res = lua_pcall(L, 1, 1, 0);
  if (res != LUA_OK) {
    /* error */
    return NULL;
  }
  return lua_tolstring(L, -1, len);
}

static int auxrequiref(lua_State *L)
{
  const char *modname = lua_tolstring(L, 1, NULL);
  lua_CFunction openf = lua_tocfunction(L, 2);
  int glb = lua_toboolean(L, 3);
  luaL_requiref(L, modname, openf, glb);
  return 1;
}

/*
** Simple version of `require` used to load modules from a C function.
*/
void hsluaL_requiref (lua_State *L, const char *modname,
                      lua_CFunction openf, int glb, int *status)
{
  lua_pushcfunction(L, &auxrequiref);
  lua_pushstring(L, modname);
  lua_pushcfunction(L, openf);
  lua_pushboolean(L, glb);
  int pstatus = lua_pcall(L, 3, 1, 0);
  if (status != NULL)
    *status = pstatus;
}