lua-users home
lua-l archive

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


[[ WARNING: Fairly dodgy techie question coming up... ]]

I'm trying to implement a reasonably efficient way to evaluate an
expression which may contain global or local variable references, but is
stored in a string.

E.g.  when given:

globalvar = "Hello"
local localvar = "World"

expr = "globalvar .. ' ' .. localvar"

expanded = magic_function( expr );

The variable 'expanded' would end up with the value "Hello World"

I have a function called __get_local which takes the name of a variable and
looks for it upwards in the locals lists (using the debug API). If it finds it,
it returns <value>, 1 and if it fails, it returns nothing.

Given all that, I have come up with the following:


function __read_value(__name)
  local __ret, __gotit = %__get_local(__name);
  if( __gotit == nil ) then
    return %rawget(%globals(), __name);
  return __ret;

__nil_tag = tag(nil)

function __getValue(__v)
  local __old_method = %settagmethod( %__nil_tag, "getglobal", %__read_value );
  local __ret = %tostring(%dostring("return " .. __v));
  %settagmethod( %__nil_tag, "getglobal", __old_method );
  return __ret;


Where __getValue() is the magic_function() in the example.

I know for a fact that this compiles down to some neat Lua such that neither of
those functions actually contains a GETGLOBAL opcode and as such, they should,
individually, be fairly damned nippy.

Does anyone have any suggestions for making it even faster (short of rewriting
it in C, which I will do if it is likely to give a serious benefit).


Daniel Silverstone                     
Hostmaster, Webmaster, and Chief Code Wibbler          Digital-Scurf Unlimited
GPG Public key available from               KeyId: 20687895
Your lucky number is 3552664958674928.  Watch for it everywhere.