Lua 修改虚拟机实战4 - function

主题:修改 Lua 第一公民 function

一份常规 Lua 代码:

print('hello')
function _add( a,b )
  return a-b
end

function _sub( a,b )
  return a+b
end

function p(...)
  local b = 2+1 *3/5
  for k,v in pairs({...}) do
      print(k,v)
  end
  print('qt',b, _add(2, 1*3/5))
end

print('3+5', _add(3,5))
print('3-5', _sub(3,5))
p('b')

执行:

$ ./src/lua ./src/optest.lua
./src/lua: ./src/optest.lua:2: '=' expected near '_add'

原因是我们修改了 function 关键字:

llex.h

#define FIRST_RESERVED  257  # 这里也可以做文章

/* maximum length of a reserved word */
#define TOKEN_LEN   (sizeof("function1")/sizeof(char))

llex.c

/* ORDER RESERVED */
const char *const luaX_tokens [] = {
    "and", "break", "do", "else", "elseif",
    "end", "false", "for", "function1", "if",
    "in", "local", "nil", "not", "or", "repeat",
    "return", "then", "true", "until", "while",
    "..", "...", "==", ">=", "<=", "~=",
    "", "", "", "",
    NULL
};

定义函数的新方式就是:

function1 _add( a,b )
  return a-b
end

optest.lua 完整版:

print('hello')
function1 _add( a,b )
  return a-b
end

function1 _sub( a,b )
  return a+b
end

function1 p(...)
  local b = 2+1 *3/5
  for k,v in pairs({...}) do
      print(k,v)
  end
  print('qt',b, _add(2, 1*3/5))
end

print('3+5', _add(3,5))
print('3-5', _sub(3,5))
p('b')

验证:

$ ./src/luac ./src/optest.lua && ./src/lua luac.out
hello
3+5 8
3-5 -2
1   b
qt  1.4 2.6

function => funciton1
function => fuck
function => fun
function => love

发挥想象力啦 ~

https://github.com/c0i/mlua5.1.5

你可能感兴趣的:(Lua 修改虚拟机实战4 - function)