1

A while ago I posted a THIS question, regarding interaction between lua.vm.js and javascript.

Now I have a slightly different problem:

Lets assume that I have the following code in the REPL

model = {}
model['test1'] = 1
model['test3'] = 2
model['test4'] = 3
model['test5'] = 4
model['test6'] = 5
local window = js.global
window.model = model

Because I'm using lua.vm.js, I now that from javascript I can get all the values by doing

window.model.get('test1')
window.model.get('test2')
window.model.get('test3')

But the problem with that is that I have to know beforehand that the entries at the table are "test1", "test2", etc.

Is there a way in javascript(or maybe by adding some more Lua code) that I can iterate all over the table without knowing all the entries?

Thanks in advance!

4
  • Does native javascript (for var in obj) looping work? Commented Jun 24, 2014 at 13:12
  • @EtanReisner: no, Lua tables are not directly represented as JavaScript objects. Commented Jun 24, 2014 at 13:14
  • In Lua you can use pairs to iterate over all of the table entries. I can't find anything for lua.vm.js though; there's very little documentation for it. Commented Jun 24, 2014 at 15:32
  • Have you looked at moonshine? I bring it up only because lua.vm.js doesn't seem to be actively developed anymore whereas the developer behind moonshine is still very active. Commented Jun 24, 2014 at 22:54

1 Answer 1

1

I think the easiest way to get the list of keys in model would be to use Lua directly.

From what I can see the lua.vm.js table object does not support iteration, but you can do that from JavaScript:

my_keys = L.execute('local r = {}; for k in pairs(model) do r[#r+1] = k end; return unpack(r)')

Then you can loop like this:

for (var i in my_keys) {
    console.log(my_keys[i], window.model.get(my_keys[i]));
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.