lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Fri, Jun 24, 2011 at 9:52 AM, Peter Odding <peter@peterodding.com> wrote:
> like Pyrex [3] for Lua. Pyrex is a programming language that looks a lot
> like Python but is closer to C and much simpler.

It would be an interesting direction, especially if one pushes static
type inference as much as possible:

function sqr (x as number)
  return x*x
end

(return type is inferred as number)

> Even just C with better macros would have helped a lot -- I find myself
> generating C code in Lua now and then because C is not a very flexible
> language at all :-)

You're not the only one! winapi was done with this preprocessor:

// preprocess using luam -C -llc str.lc > str.c
#include <string.h>

module "str" {

  def at (Str s, Int i = 0) {
    lua_pushlstring(L,&s[i-1],1);
    return 1;
  }

  def upto (Str s, Str delim = " ") {
    lua_pushinteger(L, strcspn(s,delim) + 1);
    return 1;
  }

}

which translates as:

// preprocess using luam -C -llc str.lc > str.c
#line 2 "str.lc"
#include <string.h>

#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
#ifdef WIN32
#define EXPORT __declspec(dllexport)
#else
#define EXPORT
#endif
typedef const char *Str;
typedef const char *StrNil;
typedef int Int;
typedef double Number;
typedef int Boolean;

  #line 6 "str.lc"
static int l_at(lua_State *L) {
    const char *s = luaL_checklstring(L,1,NULL);
    int i = luaL_optinteger(L,2,0);
    #line 7 "str.lc"
    lua_pushlstring(L,&s[i-1],1);
    return 1;
  }

  static int l_upto(lua_State *L) {
    const char *s = luaL_checklstring(L,1,NULL);
    const char *delim = luaL_optlstring(L,2," ",NULL);
    #line 12 "str.lc"
    lua_pushinteger(L, strcspn(s,delim) + 1);
    return 1;
  }

static const luaL_reg str_funs[] = {
       {"at",l_at},
   {"upto",l_upto},
    {NULL,NULL}
};

EXPORT int luaopen_str (lua_State *L) {
    luaL_register (L,"str",str_funs);
    return 1;
}

That is, it does all the boilerplate which I can never keep in my head
for long.  Good for checking out something quickly, like in this case,
'is str.at(s,i) particularly faster than s:sub(1,1)?"

It gets particularly interesting when implementing Lua 'classes' but I
won't bore the list further with my enthusiasms.

steve d.