lua-users home
lua-l archive

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


Dirk Laurie wrote:
<snip>
> Trouble is, I can't see a way to write a C function "self" that 
> can be imported into the global namespace and would achieve this.
> "self" would have to be an implicitly defined local variable 
> referring to the function under construction, created by the Lua 
> compiler: in effect, a reserved word.  
<snip>

I missed the "C" part. Here's one solution, just for completeness:

/* self.c */
#include <lua.h>

static int self (lua_State *L) {
  int n = lua_gettop(L);
  lua_Debug ar;
  lua_getstack(L, 1, &ar); /* function calling `self' */
  lua_getinfo(L, "f", &ar); /* push function */
  lua_insert(L, -(n+1));
  lua_call(L, n, LUA_MULTRET);
  return lua_gettop(L);
}

int luaopen_self (lua_State *L) {
  lua_pushcfunction(L, self);
  return 1;
}

Test:

Lua 5.1.4  Copyright (C) 1994-2008 Lua.org, PUC-Rio
> self = require"self" -- fine as long as you don't use ":"
> f = function(n) if n<2 then return 1 end return n*self(n-1) end
> print(f(5))
120
> fib = function(n) if n<3 then return n-1 end return self(n-1) +
self(n-2) end
> print(fib(10))
34

Another option is a getter:

static int getself (lua_State *L) {
  lua_Debug ar;
  lua_getstack(L, 1, &ar); /* function calling `self' */
  lua_getinfo(L, "f", &ar); /* push function */
  return 1;
}

Cheers,
Luis

-- 
Computers are useless. They can only give you answers.
                -- Pablo Picasso

-- 
Luis Carvalho (Kozure)
lua -e 'print((("lexcarvalho@NO.gmail.SPAM.com"):gsub("(%u+%.)","")))'