Evaluating Mathematical Expressions using Lua

前端 未结 5 528
不知归路
不知归路 2021-01-18 20:00

In my previous question I was looking for a way of evaulating complex mathematical expressions in C, most of the suggestions required implementing some type of parser.

5条回答
  •  既然无缘
    2021-01-18 20:32

    This is for Lua users that are looking for a Lua equivalent of "eval".

    The magic word used to be loadstring but it is now, since Lua 5.2, an upgraded version of load.

     i=0
     f = load("i = i + 1") -- f is a function
     f() ; print(i) -- will produce 1
     f() ; print(i) -- will produce 2
    

    Another example, that delivers a value :

    f=load('return 2+3')
    print(f()) -- print 5
    

    As a quick-and-dirty way to do, you can consider the following equivalent of eval(s), where s is a string to evaluate :

    load(s)()
    

    As always, eval mechanisms should be avoided when possible since they are expensive and produce a code difficult to read. I personally use this mechanism with LuaTex/LuaLatex to make math operations in Latex.

提交回复
热议问题