---
title: "lua通过loadstring实现eval和lambdal表达式"
author: "gukeming888"
date: "2013-08-07T16:45:36Z"
tags: []
categories: ["编程语言"]
slug: "lua-loadstring-eval-lambdal"
draft: false
lastmod: "2013-08-07T16:45:36Z"
id: 1921586
url: "https://gukeming888.iteye.com/blog/1921586"
---

function eval(str)
    if type(str) == "string" then
        return loadstring("return " .. str)()
    elseif type(str) == "number" then
        return loadstring("return " .. tostring(str))()
    else
        error("is not a string")
    end
end

function lambda(lambda_string,...)
--验证是否仅存在一个：号
    pos = string.find(lambda_string,":")
    if pos ~= nil then
        if string.find(lambda_string,":",pos+1)~= nil then
            error('more than one ":"')
         end
    end
    if type(lambda_string) ~= "string" then
        error("is not a string")
    end
    --lambda x:x+x 将其分割为 参数 x 和 表达式 x+x 的形式
    parameter = string.sub(lambda_string,1,pos-1)
    expression = string.sub(lambda_string,pos+1,-1)

    fun = string.format("return function(%s) return %s end",parameter,expression)
    local func = loadstring(fun)()(...)
	return func
end