Giter Club home page Giter Club logo

lua.vm.js's Introduction

lua.vm.js

The Lua VM, on the Web

Online demo: http://daurnimator.github.io/lua.vm.js/lua.vm.js.html

Status

This began as an experiment to see how fast the Lua VM can run on the web. That was successful (performance is quite good in both firefox and chrome).

Next step is to iterate on the Lua <=> JS interoperability. Clever solutions to the lack of finalisers in Javascript are being searched for.

Building

To build, run make emscripten in the lua subdirectory

Usage from NodeJS

$ npm install lua.vm.js

And inside your script:

var LuaVM = require('lua.vm.js');

var l = new LuaVM.Lua.State();
l.execute('print("Hello, world")');

License

This project is MIT/X11 licensed. Please see the COPYING file in the source package for more information.

Copyright (c) 2013 Alon Zakai (kripken)
Copyright (c) 2014-2016 Daurnimator

Lua is licensed under MIT.

lua.vm.js's People

Contributors

dark7god avatar daurnimator avatar ianmaclarty avatar kripken avatar seanjensengrey avatar statico avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

lua.vm.js's Issues

Samples usage

Hello,

didn't know where to share this. I am currently working on basic and non basic samples for showing lua used with lua.vm.js .

Here is my repo Lua.vm.js-Samples

There is still some work to make more samples but I think a repo like this could have help me at the beginning.

Unable to pass objects between Lua and JS

<script>
var obj={k:7,"9":0};
</script>
<script src=lua.vm.js></script>
<script type=text/lua>
print(js.global.obj)            -- works
print(js.global.obj["k"])       -- works
print(js.global.obj["9"])       -- Uncaught SyntaxError: Unexpected number 
js.global.console.log{4,5,6}    -- Uncaught SyntaxError: Unexpected token <
js.global.console.log(js.new.Array(3))          -- ditto
</script>

Unable to call jQuery(document).ready() from Lua

Hello,

First of all, let me tell you that this project is super exciting! I am working on server-side Lua proramming (LSP), but being able to write client-side scripting in Lua without any pre-compilation (unlike the Moonshine project) is a big plus! Please keep maintaining and improving this project. It has a tremendous amount of potential, as porting Lua to essentially all web browsers opens up a world of possibilities!

I was testing whether I could re-use jQuery without having to re-write it in Lua completely. Using the $ variable doesn't work, probably because this is an invalid variable name in Lua. Luckily, jQuery provides a global variable called jQuery, so simple things like js.global.jQuery("#divid").html("This is JQuery from Lua!!!") work fine. However, js.global.jQuery(js.global.document).ready(function() ... end) doesn't work, giving a cryptic "SyntaxError" error on lua.vm.js:6624.

I suspect this maybe because I'm trying to pass a Lua function object to a JavaScript function that expects a JS function object, and this conversion may not be supported. Any thoughts?

Regards,

Gabriel Mongefranco
Software Developer
http://gabriel.mongefranco.com

Off by one error in argument passing to Javascript

Test case:

function test(a,b) {console.log(a); console.log(b);};
test("a", "b");
VM1485:1 a
VM1485:1 b
undefined
L.execute("js.global.test('a', 'b')");
VM1485:1 b
VM1485:1 undefined
[]
L.execute("js.global.test(nil, 'a', 'b')");
VM1485:1 a
VM1485:1 b
[]

Testing null value

Hello guys, I am trying to test if a node exist or not.

local d = js.global.document:getElementById("test")
print(d) -- return null
if d then
  print(d.innerHTML) -- return Uncaught Lua.Error: TypeError: Cannot read property 'innerHTML' of null
end

In my page the id test doesn't exist but the if is always executed. How do you check for null and/or undefined value from lua code ?

Unable to Call HTTP Request Methods from NodeJS

Hello,

local jq = window.jQuery()
print("version", jq.jquery)
print("version second call", jq.jquery)
local jqxhr = window.jQuery:get("/glossary.json")
jqxhr:done(function() print(jqxhr.responseText) end)

Since there isn't the Window object in NodeJS how can I call JQuery ajax get/post in lua.vm.js?

local jq = js.get("$")
local jqxhr = jq.get("/glossary.json")
jqxhr.done(function() print(jqxhr.responseText) end)

I had tried the code above that catch the follow exception:
e:Lua.Error: [string "?"]:5: attempt to call field 'get' (a nil value)

IO Library

This is more of a question than an issue:
I have some .txt files that I would like to open from lua but the io library is not working. Any hints on how to do this?

Consider removing file operations

The features of stdio don't make a lot of sense inside of javascript (especially the browser).

Lets see how things work without touching the filesystem...

  • io library , loadfile, dofile removed
  • print needs to change to console.log or similar
  • package library will loose default path searchers
  • debug.debug won't work
  • panic function needs to change to console.error or similar

Will also need to update webpage and examples

Simple value passing between Javascript and Lua get strange results

From the Chrome console:

function myfnc() { return [1,2,3]; }

Lua.execute("r = js.global.myfnc(); print(r); for k,v in pairs(r) do print(k,v) end")
table: 0x506ef0
index 3

// I expected to see my 1,2,3 values printed out.

function myfnc() { return null; }
Lua.execute("r = js.global.myfnc(); print(r);")
table: 0x508c20

// I expected to see nil printed out.

abort in REPL.

for k,v in pairs(js.global) do
  print(k, v)
end

in the REPL example fails with:

abort(4) at Error
    at jsStackTrace (https://kripken.github.io/lua.vm.js/lua.vm.js:1:28127)
    at stackTrace (https://kripken.github.io/lua.vm.js/lua.vm.js:1:28310)
    at abort (https://kripken.github.io/lua.vm.js/lua.vm.js:15:13917)
    at Array.cp (https://kripken.github.io/lua.vm.js/lua.vm.js:8:37151)
    at xf (https://kripken.github.io/lua.vm.js/lua.vm.js:5:19747)
    at sg (https://kripken.github.io/lua.vm.js/lua.vm.js:5:68029)
    at tg (https://kripken.github.io/lua.vm.js/lua.vm.js:5:71170)
    at vg (https://kripken.github.io/lua.vm.js/lua.vm.js:5:72977)
    at Pc (https://kripken.github.io/lua.vm.js/lua.vm.js:7:24027)
    at Zh (https://kripken.github.io/lua.vm.js/lua.vm.js:6:4030)
If this abort() is unexpected, build with -s ASSERTIONS=1 which can give more information.

Javascript messages are hijacked/wrong after loading lua.vm.js

This problem occur only when invoking a script from a file, and does not show when invoking node interactively.

Suppose you have a javascript file (i.e. named 'undefTest.js') with an error inside (i.e. calling an undefined function):

functionNotDefined();

If you launch it:

$ node undefTest.js 
/home/fabrizio/working/git/lua.vm.js/undefTest.js:1
functionNotDefined();
^
ReferenceError: functionNotDefined is not defined
    at Object.<anonymous> (/home/fabrizio/working/git/lua.vm.js/undefTest.js:1:1)
    at Module._compile (module.js:460:26)
   ...

But suppose in this undefTest.js you load lua.vm.js before invoking the undefined function:

var L=require('./dist/lua.vm.js').L
functionNotDefined();

Now, when launching it, node shows some different error message generated by lua.vm.js:

$ node undefTest.js 
/home/fabrizio/working/git/lua.vm.js/dist/lua.vm.js:2
aughtException",(function(ex){if(!(ex instanceof ExitStatus)){throw ex}}));Mod
                                                                    ^
ReferenceError: functionNotDefined is not defined
    at Object.<anonymous> (/home/fabrizio/working/git/lua.vm.js/undefTest.js:2:1)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)

Avoid synchronous JavaScript operations?

The load_lua_over_http function makes a synchronous call to XMLHttpRequest. As it is considered as a bad practice, an asynchronous call could be preferred.

This example shows how the usual imperative style of Lua can be used together with JavaScript's callbacks. This solution does not handle well errors. It also requires that the main Lua code is executed within a coroutine. This could be done automatically by L.execute, for instance.

Warning: using coroutines within coroutines in Lua can lead to wrong behavior (from the programmer's point of view). If a JavaScript asynchronous operation does a yield within a coroutine implemented iterator, the yield will be caught by the iterator instead of the main function. Philipp Janda and i have proposed a workaround in lua-coronest.

Use a testsuite

We need tests!

I'm not sure what the best testing tool/infrastructure will be here.
Do people have suggestions?

Crash On iPhone 4S(IOS 6.1?)

Nothing to report. Crash entire safari application. The sample script page works on ios simulator and old retina ipad.

Please let me know, if there are any way to debug that crash.

Anyway, I'm very exciting about this project. I really do need lua's coroutine.

local window = js.global

function sleep(seconds)
  local co = coroutine.running()
  window.setTimeout(function()
      coroutine.resume(co)
  end
  , seconds * 1000)
  coroutine.yield()
end

coroutine.wrap(function()
    print("Sleeping...")
    sleep(1)
    print("This is the lua's coroutine")
end)()

Require doesn't work as expected

Issue with lua modules and require.

First of all I'd like to say that this is an awesome project.
The problem is I may be doing something wrong here, so please correct me if this is not the right way.

I have index.html the page from which I want to load (require) the test.lua module.

The problem is that I'm getting this output in chromium's Console.
Which leads me to believe that requiring doesn't work exactly as it should.
I have also tried to append to the packages.path variable with no luck. :(

Am I doing something wrong?

For ease of access:

  • index:
    <!doctype html>
    <html>
    <head>
    <meta charset="UTF-8" />
    <title>Simple Lua Require Test</title>
    <script type="text/javascript" src="lua.vm.js"></script>
    <script type="text/lua" src="test.lua"></script>
    </head>
    <body>
        <script type="text/lua">
            test = require("test")
            print(test.test_function("some_value"))
        </script>
    </body>
    </html>
  • lua:
    local function some_function(some_value)
        return 'some_function("' .. some_value .. '")'
    end

    return {
        test_function = some_function
    }
  • output:
    preload time: 3 ms lua.vm.js:99  
    ERROR: [string "input"]:2: module 'test' not found:     lua.vm.js:96  
        no field package.preload['test']                    lua.vm.js:96  
        no file '/usr/local/share/lua/5.2/test.lua'         lua.vm.js:96  
        no file '/usr/local/share/lua/5.2/test/init.lua'    lua.vm.js:96  
        no file '/usr/local/lib/lua/5.2/test.lua'           lua.vm.js:96  
        no file '/usr/local/lib/lua/5.2/test/init.lua'      lua.vm.js:96  
        no file './test.lua'                                lua.vm.js:96 << 
        no file '/usr/local/lib/lua/5.2/test.so'            lua.vm.js:96  
        no file '/usr/local/lib/lua/5.2/loadall.so'         lua.vm.js:96  
        no file './test.so'                                 lua.vm.js:96

AJAX callbacks are firing but data is not returned

Fantastic piece of software with a huge potential for replacing JavaScript in the browser!

A few snippets of code collected from the mailing list, wiki, issues, etc. Everything works out of the box with no perceived performance impact. I only have problems with callback return values on JQuery ajax calls and WebSockets returned message.

For example (see script_example.html below):

js.run('$.get("/glossary.json", function(data) { console.log(data); });') -- this works
jq.get("/glossary.json", function(data) print(data) end) -- the callback is firing, but data is not returned

A workaround using the load() function:

jq('#result').hide().load("/glossary.json", function() print(jq('#result').html()) end) -- this works because after the callback is fired, we just collect the result from the result div

The following goes into script_example.html:

<!-- begin script tag example -->

<script src="lua.vm.js"></script>
<script src="jquery-1.10.1.js"></script>

<!--
  Simplest web server for serving static files
  python -m SimpleHTTPServer 8080
-->

<script type="text/lua">
-- Print contents of `tbl`, with indentation.
-- `indent` sets the initial level of indentation.
function tprint (tbl, indent)
  if not indent then indent = 0 end
  for k, v in pairs(tbl) do
    formatting = string.rep("  ", indent) .. k .. ": "
    if type(v) == "table" then
      print(formatting)
      tprint(v, indent+1)
    else
      print(formatting .. tostring(v))
    end
  end
end

-- function test()
--   return 'ok'
-- end
-- for i=1,5 do
--   js.global.alert(test())
-- end

local jq = js.get("$")
-- jq('body').append("plop").click(function() js.global.alert("plop click") end)
-- local version = jq().jquery
-- js.global.alert(version)
-- jq('#result').load("/glossary.json")
jq('#result').hide().load("/glossary.json", function() print(jq('#result').html()) end)
-- jq.get("/glossary.json", function(data) print(data) end) -- callback is firing, but data is not returned
-- js.run('$.get("/glossary.json", function(data) { console.log(data); });')

-- coroutine example
-- local window = js.global
--
-- function sleep(seconds)
--   local co = coroutine.running()
--   window.setTimeout(function()
--     coroutine.resume(co)
--   end
--   , seconds * 1000)
--   coroutine.yield()
-- end
--
-- coroutine.wrap(function()
--   print("Sleeping...")
--   sleep(1)
--   print("This is the lua's coroutine")
-- end)()

-- local ws = js.new.WebSocket("ws://echo.websocket.org/?encoding=text")
-- ws.onopen = function()
--   print("connected!")
--   ws.send("Rock it with HTML5 WebSocket")
-- end
-- ws.onclose = function()
--   print("disconnected")
-- end
-- ws.onerror = function(error)
--   print(error)
-- end
-- ws.onmessage = function(e)
--   tprint(e)
--   ws.close()
-- end
</script>

<!-- end script tag example -->

<div id="result"></div>

The glossary.json file loaded in the examples above:

{
    "glossary": {
        "title": "example glossary",
        "GlossDiv": {
            "title": "S",
            "GlossList": {
                "GlossEntry": {
                    "ID": "SGML",
                    "SortAs": "SGML",
                    "GlossTerm": "Standard Generalized Markup Language",
                    "Acronym": "SGML",
                    "Abbrev": "ISO 8879:1986",
                    "GlossDef": {
                        "para": "A meta-markup language, used to create markup languages such as DocBook.",
                        "GlossSeeAlso": ["GML", "XML"]
                    },
                    "GlossSee": "markup"
                }
            }
        }
    }
}

Strange object interaction between Lua <--> JS

TL;DR: After getting access to jQuery object from javascript into lua, early operations performed on that object causes subsequent operations to fail with !Unsupported! string being returned instead of the actual desired output.

I encountered this strange problem while testing out issue #5. I have the following simple html with some embedded Lua using jQuery:

<html>
  <head>
    <title>script example</title>
  </head>

  <script src="lua.vm.js"></script>  
  <script src="jquery-2.0.3.js"></script>

  <script type="text/lua">
  local jq = js.get("$")

  local jqxhr = jq.get("./glossary.json")
  jqxhr.done(function() print(jqxhr.responseText) end)
  </script>
</html>

This parses the json file and prints it to console.log as expected. However, if I add some intermediate code, like getting jquery version, then things start failing in mysterious ways:

...
local jq = js.get("$")
local version = jq().jquery
print(version, '********')

local jqxhr = jq.get("./glossary.json")
jqxhr.done(function() print(jqxhr.responseText) end)
...

The jq().jquery call succeeds and the version gets printed but jqxhr.done fails:

ERROR: [string "input"]:14: attempt to call field 'done' (a string value)

In fact, jqxhr.done will contain the string '!Unsupported!'. Calling that like it's a function causes the above error.

If I switch the order of the statements to this:

...
local jq = js.get("$")
local jqxhr = jq.get("./glossary.json")
local version = jq().jquery

print(version, '********')
jqxhr.done(function() print(jqxhr.responseText) end)
...

Then jqxhr.done has the right object again and the json parse results get printed like before. However, now the call jq().jquery fails and version will contain "!Unsupported!" instead of the expected jQuery version string.

What could be causing this bizarre behavior? This can be reproduced with jQuery 1.10.x as well as jQuery 2.0.x.

Just Offering my Knowledge

The page had a link to 'issues' for getting in touch, so I must assume that's how you'd prefer I do so. I'm currently working on a very cross-platform game engine, which will include an implementation of Lua, so that games can be written in Lua, and run on the engine. One implementation of the engine is in JavaScript, so a Lua VM in JS is a must! Seeing this, and how fast it can be, I fell in love. So, I'm offering any help I can to make this project the best it can be. If you'd like my Email, just say so. I'm looking forward to hearing from you.

Cannot pause interpretor main loop

I'm trying to implement browser side functions that require user input, in a friendly non browser blocking way.

For this i'm using the lua vm inside a webworker thread that sends an execution request to a "DOMland" function and then should suspend the execution until the webworker is notified that a return value is present.

That return value would then need to be injected into the stack, and the execution resumed.

My problem is that Module.pauseMainLoop() doesn't affect the execution in any way. And i suspect that its because ccall is used.

Loading compiled byte code

I'm trying to load byte code directly using loadbufferx but always get a result of 3 (LUA_ERRSYNTAX). What kind of object to you have to pass to loadbufferx? I've tried Uint8Array et al but none seem to work.

FYI the file is compiled using the bundled luac and doing this in C works as expected.

Any thoughts?

js.global is not initialized correctly when used within node.js

js.global works fine if used into the browser, but if you try to access it from a node.js application it generate an exception.

To reproduce the error, create a test.js file:

function executeLua(L,code) {
  try {
    L.execute(code);
  } catch(e) {
    console.log(e.toString());
  }
}

function test1(){
  var LuaVM = require('lua.vm.js');
  var L = new LuaVM.Lua.State();
  var theCode =
  "print(js.global:eval('[0,1,2,3,4,5][3]'))"
  var result = executeLua(L,theCode)
}

function test2(){
  var LuaVM = require('lua.vm.js');
  var L = new LuaVM.Lua.State();
  var theCode =
  "print(js.global.console:log('hello'))"
  var result = executeLua(L,theCode)
}

test1()
//test2()

and execute it by running:

node test.js

you will get the following exception:

Lua.Error: [string "?"]:1: attempt to call method 'eval' (a nil value)

or, for test2:

Lua.Error: [string "?"]:1: attempt to index field 'console' (a nil value)

Issue #30 started the discussion about this issue

Cannot run Lua function from JS with arguments

<script src=lua.vm.js></script>
<script>
    runFunc = function(func, args) {
        func(args) // Runs the function with arguments
    }
</script>

<script type=text/lua>
    function echo(x) -- Simple echo function
        print(x)
    end

    js.global.runFunc(echo, 'hi there') -- Run function from JS with arguments
</script>

If I run this then inside the console it would just print table: 0x50ca28 and the table would be empty. Am I doing something wrong?

One argument not being passed.

Observe:

script

  inject_js(this.l, function() {
    console.log(arguments);
  }, "test_args")

inject_js

function inject_js(state, code, global) {
  state.pushjs(code);
  state.setglobal(global);
  state.pop(0); // may or may not be needed.
}

lua

test_args("hello", "world")

output:

{ '0': 'world' }

Hope that sums this up!

Assigning nil to js variable crashes

Test code:

js.global.test = nil

Fails with (in Chrome):

Uncaught SyntaxError: Unexpected token <      : lua.vm.js.:3090

Is this by design? Any more information about that issue?

0.0.1 crashes when trying to [i]pairs a js array

Hi. Pretty simple reproduction. Using 0.0.1 via npm, will try master soon.

nodejs only

var array = [ 'item', 'item2', 'item3'];
local arr = myFuncToGetJSArray();
for i, v in ipairs(arr) do
   print(v)
end

Pure Lua:

local tble      = {}
tble[1]         = 'item';
tble[2]         = 'item2';
local arr = js.global:Array(table.unpack(tble))
for i, v in ipairs(arr) do
   print(v)
end

EDIT: self built from master fails as well.

type "boolean" in the JS <--> LUA

Type "boolean" is not handled in "js.to_js" function = this throws an exception when used. It's horribly hackish (as stated in "js.lua" !), but it can added like this:

js.to_js = function(x)
   if type(x) == 'number' or type(x) == 'boolean' then return tostring(x)
   ...

Then rebuild your "lua.vm.js" file.
It works for me but there is probably a better solution!

Reading Lua variables into Javascript

Hi!

I don't know if this is an ongoing project, but maybe someone out there knows the anwser.

I'm using the REPL example to test some code:
local key = {}
local data = {
[key] = "something",
a = { b = 3 },
}
local v1 = data [key]
local v2 = data.a.b
print(v1)
print(v2)

Everything works fine(I get the ouput in the ouput window), but now I'm trying to get those values into Javascript.
I mean: Have variables called key, data, v1, etc. with the information from the lua script.

Is that possible?

I'm reading the code from lua.vm.js but I cant find anything like it.

Thanks in advance!

Hope to hear from someone

Best way to debug?

Hi, I'm having trouble running a lua script under the VM. I've successfully tested the VM with simple code, and my script works running it normally with lua. I've escaped all single-quotes in the script with \x27, and I made sure the string of code is all in one piece. Am I missing something, any rules of thumb? The reason I'm not posting any code specifically is that it's quite a long script, but I can pastebin it if you'd like. Thanks.

Lua 5.1

Lua 5.1 is still widespread (and we maintain quite a lot of code in it), and Lua 5.2 still does not have as wide module support as one would like it to.

So. Can we get lua5.1.vm.js, please?

io.open not working

I am trying to execute, from node, a simple chunk of lua code that has to open a file and print the content on the screen. Here how to reproduce it:

var LuaVM = require('lua.vm.js');
var L = new LuaVM.Lua.State();

var theCode = "local myFile, err = io.open('/tmp/file.txt') \
    if not myFile then print(err) return end \
    io.input(myFile) \
    local theContent = io.read('*all') \
    print(theContent)"

var result = L.execute(theCode)
console.log(result)

The output is:

/tmp/file.txt: No such file or directory
[]

I verified that the file /tmp/file.txt exists.

Script code not executed when using src attribute

Hi guys,

I am trying to use lua.vm.js in my web site.

If i add directly the code inside the script tags like so :

<script src="/static/js/lua.vm.js"></script>
<script type="text/lua">
js.global:alert('hello from Lua script tag in HTML!') -- this is Lua!
</script>

It's fully working.

But if I try to add it using the src attribute, it's not executed

<script src="/static/js/lua.vm.js"></script>
<script type="text/lua" src="/static/lua/app.lua"></script>

Here is my app.lua file :

js.global:alert('hello from Lua script tag in HTML!') -- this is Lua!

Uncaught Lua.Error: attempt to call a nil value

Hi @daurnimator
after this commit b363f4e we have an error "Uncaught Lua.Error: attempt to call a nil value" when we call send method of an XMLHttpRequest object

Here is an example of code which does not work

<script type="text/javascript" lang="JavaScript" src="https://rawgit.com/daurnimator/lua.vm.js/b363f4e26e7a3df749c3dc305c1fb7eb90b62a99/dist/lua.vm.js"></script>
  <script type="text/lua" lang="Lua" id="luascript">
  local function main()
    local co, sync = coroutine.running ()
    local request = _G.js.new (_G.window.XMLHttpRequest)
    request:open ("GET", "/html/sandbox.html", true)
    local result, err
    request.onreadystatechange = function (event)
      if request.readyState == 4 then
        if request.status == 200 then
          result = request.responseText
        else
          err    = event.status
        end
        coroutine.resume (co)
      end
    end
    request:send ()
    coroutine.yield ()
  end
  local co = coroutine.create (main)
  coroutine.resume (co)
  </script>

Thanks

Question about AddEventListener and general callbacks

Hello I am trying to prevent a form to be submit.
Here is my code.

function init()
  local form = document:querySelector(".to-validate")
  if notNullJs(form) then

    form:addEventListener(
      "submit",
      function (event)
        print(event)
        event:preventDefault()
      end,
      false)
  end
end

When I submit the form, I always got this error: Lua.Error: [string "validator.lua"]:12: attempt to call method 'preventDefault' (a nil value)

Can you explain me what I am doing wrong ? And also, if this is possible to define the callback as a standard function outside of addEventListener

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.