split @load apart, add @run

This commit is contained in:
leaf corcoran
2014-02-01 11:59:22 -08:00
parent 8b67327708
commit f2a819b7f4
2 changed files with 41 additions and 27 deletions

View File

@@ -169,7 +169,14 @@ do
if not (success) then
return nil, err
end
return self:load(self:chunks_to_lua())
local fn
fn, err = self:load(self:chunks_to_lua())
if not (fn) then
return nil, err
end
return function(...)
return self:run(fn, ...)
end
end,
parse = function(self, str)
self.str = str
@@ -230,25 +237,26 @@ do
end
return nil, err
end
return function(env, buffer)
if env == nil then
env = { }
end
if buffer == nil then
buffer = { }
end
local combined_env = setmetatable({ }, {
__index = function(self, name)
local val = env[name]
if val == nil then
val = _G[name]
end
return val
end
})
setfenv(fn, combined_env)
return fn(buffer, #buffer, tostring, concat, html_escape)
return fn
end,
run = function(self, fn, env, buffer)
if env == nil then
env = { }
end
if buffer == nil then
buffer = { }
end
local combined_env = setmetatable({ }, {
__index = function(self, name)
local val = env[name]
if val == nil then
val = _G[name]
end
return val
end
})
setfenv(fn, combined_env)
return fn(buffer, #buffer, tostring, concat, html_escape)
end,
chunks_to_lua = function(self)
local buffer = {

View File

@@ -132,7 +132,9 @@ class Parser
compile: (str) =>
success, err = @parse str
return nil, err unless success
@load @chunks_to_lua!
fn, err = @load @chunks_to_lua!
return nil, err unless fn
(...) -> @run fn, ...
parse: (@str) =>
assert type(@str) == "string", "expecting string for parse"
@@ -163,6 +165,7 @@ class Parser
source_line = get_line @str, source_line_no
"#{err_msg} [#{source_line_no}]: #{source_line}"
-- converts lua string into template function
load: (code, name="etlua") =>
code_fn = do
code_ref = code
@@ -179,14 +182,17 @@ class Parser
return nil, err
(env={}, buffer={}) ->
combined_env = setmetatable {}, __index: (name) =>
val = env[name]
val = _G[name] if val == nil
val
fn
setfenv fn, combined_env
fn buffer, #buffer, tostring, concat, html_escape
-- takes a function from @load and executes it with correct parameters
run: (fn, env={}, buffer={}) =>
combined_env = setmetatable {}, __index: (name) =>
val = env[name]
val = _G[name] if val == nil
val
setfenv fn, combined_env
fn buffer, #buffer, tostring, concat, html_escape
-- generates the code of the template
chunks_to_lua: =>