lua-users home
lua-l archive

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


I have a little project where I turn pages like...

[Lua]$ cat test1.html
<html>
       <head>
               <title>This is a test Lua page</title>
       </head>
       <body>
<p>Todays date is [% io.write(os.date("%Y/%m/%d %H:%M:%S")) %]</p>
               <p>We can also calculate 1 + 1 = [% io.write(
1
+
1
)%]</p>
               <p>And now a list:</p>
               <ol>
[%  a = {'tom', 'dick', 'harry'}
       for i,v in ipairs(a) do %]
                       <li>[% io.write(v) %]</li>
[%  end%]
               </ol>
               <p>[% x = 42 %]Here we set x to [% io.write(x) %]</p>
       </body>
</html>
[Lua]$

into functions...
io.write("<html>\n <head>\n <title>This is a test Lua page</title>\n </head>\n <body>\n <p>Todays date is ")
io.write(os.date("%Y/%m/%d %H:%M:%S"))
io.write("</p>\n                <p>We can also calculate 1 + 1 = ")
io.write( 1 + 1 )
io.write("</p>\n <p>And now a list:</p>\n <ol>\n")
a = {'tom', 'dick', 'harry'}  for i,v in ipairs(a) do
 io.write("                      <li>")
 io.write(v)
 io.write("</li> \n")
end
io.write("              </ol>\n         <p>")
x = 42
io.write("Here we set x to ")
io.write(x)
io.write("</p>\n        </body>\n</html>\n")

Which when called will render the page...
<html>
       <head>
               <title>This is a test Lua page</title>
       </head>
       <body>
               <p>Todays date is 2004/03/29 21:44:37</p>
               <p>We can also calculate 1 + 1 = 2</p>
               <p>And now a list:</p>
               <ol>
                       <li>tom</li>
                       <li>dick</li>
                       <li>harry</li>
               </ol>
               <p>Here we set x to 42</p>
       </body>
</html>

I can store the function in a table and call whenever I need to display the page. A bit like JSP or Mason.

The problem that I have is shown in the following example which strips things down...
[Lua]$ cat example.lua
#!/usr/local/bin/lua

s1 = "x = 42"
s2 = "print(x)"

c1 = loadstring(s1)
c2 = loadstring(s2)

c2()
c1()
c2()
[Lua]$

When I run this I get
nil
42
as the output. But what I really want is
nil
nil

I want the scope of c1 to be independent of c2. Now in the example I could use
s1 = "local x = 42"
but in the LSP's (Lua Server Pages perhaps) I don't want the programmer to have to explicitly scope all their variables as local because 1, its a real pain and 2, some are going to slip through and make for a very difficult bug. Any ideas how I might wrap the compiled functions (c1 and c2) up so that all the variables they use are local to the functions?