EzDevInfo.com

lua interview questions

Top lua frequently asked interview questions

How do I get the number of keys in a hash table in Lua?

myTable = {}
myTable["foo"] = 12
myTable["bar"] = "blah"
print(#myTable) -- this prints 0

Do I actually have to iterate through the items in the table to get the number of keys?

numItems = 0
for k,v in pairs(myTable) do
    numItems = numItems + 1
end
print(numItems) -- this prints 2

Source: (StackOverflow)

Lua - merge tables?

I need to merge two tables, with the contents of the second overwriting contents in the first if a given item is in both. I looked but the standard libraries don't seem to offer this. Where can I get such a function?


Source: (StackOverflow)

Advertisements

How to remove a lua table entry by its key?

I have a lua table that I use as a hashmap, ie with string keys :

local map = { foo = 1, bar = 2 }

I would like to "pop" an element of this table identified by its key. There is a table.remove() method, but it only takes the index of the element to remove (ie a number) and not a generic key. I would like to be able to do table.remove(map, 'foo') and here is how I implemented it :

function table.removekey(table, key)
    local element = table[key]
    table[key] = nil
    return element
end

Is there a better way to do that ?


Source: (StackOverflow)

Lua - Current time in milliseconds

another Lua question: Is there a common way to get the current time in or with milliseconds? There is os.time(), but it only provides full seconds.


Source: (StackOverflow)

Lua string to int

How can I convert a string to an integer in Lua? Thank you.

I have a string like this:

a = "10"

I would like it to be converted to 10, the number.


Source: (StackOverflow)

Why does Lua have no "continue" statement?

I have been dealing a lot with Lua in the past few months, and I really like most of the features but I'm still missing something among those:

  • Why is there no continue?
  • What workarounds are there for it?

Source: (StackOverflow)

Split string in lua?

I need to do a simple split of a string, but there doesnt seem to be a function for this, and the manual way i tested didn't seem to work. How would i do it?


Source: (StackOverflow)

Lua as a general-purpose scripting language?

When I see Lua, the only thing I ever read is "great for embedding", "fast", "lightweight" and more often than anything else: "World of Warcraft" or in short "WoW".

Why is it limited to embedding the whole thing into another application? Why not write general-purpose scripts like you do with Python or Perl?

Lua seems to be doing great in aspects like speed and memory-usage (The fastest scripting language afaik) so why is it that I never see Lua being used as a "Desktop scripting-language" to automate tasks? For example:

  • Renaming a bunch of files
  • Download some files from the web
  • Webscraping

Is it the lack of the standard library?


Source: (StackOverflow)

Capabilities for Lua: what experience is there?

There's been some discussion on the cap-talk mailing list around whether Lua and Javascript support the object-capability model, with the conclusion that because of support for restricting the environment to called functions through setfenv, and the possibility of unforgeable references to immutable objects, the OCM could be implemented.

Have we seen how this works out? I'm interested in removing exploits from an existing application with very useful, generous scripting support in Lua that unfortunately allows full shell access in all kinds of cases. Some shell access is needed: the object-capability model seems like a good way to manage things. But I worry about how convincing a case I can make that this approach will actually be verifiably secure in the sure-to-be messy practice.

Some links:

  1. Older SO question: How can I create a secure Lua sandbox?
  2. Background at erights.org: From Objects To Capabilities
  3. Lua wiki: SandBoxes and ReadOnlyTables - shows setfenv in action; shows basic idea behind tables that can, under the right circumstances, be made read only

Source: (StackOverflow)

Get back the output of os.execute in Lua

When I do an "os.execute" in Lua, a console quickly pops up, executes the command, then closes down. But is there some way of getting back the console output only using the standard Lua libraries?


Source: (StackOverflow)

What web server to use for Lua web development [closed]

What web server (and why) should I use for Lua web development?


Source: (StackOverflow)

What multithreading package for Lua "just works" as shipped?

Coding in Lua, I have a triply nested loop that goes through 6000 iterations. All 6000 iterations are independent and can easily be parallelized. What threads package for Lua compiles out of the box and gets decent parallel speedups on four or more cores?

Here's what I know so far:

  • luaproc comes from the core Lua team, but the software bundle on luaforge is old, and the mailing list has reports of it segfaulting. Also, it's not obvious to me how to use the scalar message-passing model to get results ultimately into a parent thread.

  • Lua Lanes makes interesting claims but seems to be a heavyweight, complex solution. Many messages on the mailing list report trouble getting Lua Lanes to build or work for them. I myself have had trouble getting the underlying "Lua rocks" distribution mechanism to work for me.

  • LuaThread requires explicit locking and requires that communication between threads be mediated by global variables that are protected by locks. I could imagine worse, but I'd be happier with a higher level of abstraction.

  • Concurrent Lua provides an attractive message-passing model similar to Erlang, but it says that processes do not share memory. It is not clear whether spawn actually works with any Lua function or whether there are restrictions.

  • Russ Cox proposed an occasional threading model that works only for C threads. Not useful for me.

I will upvote all answers that report on actual experience with these or any other multithreading package, or any answer that provides new information.


For reference, here is the loop I would like to parallelize:

for tid, tests in pairs(tests) do
  local results = { }
  matrix[tid] = results
  for i, test in pairs(tests) do
    if test.valid then
      results[i] = { }
      local results = results[i]
      for sid, bin in pairs(binaries) do
        local outcome, witness = run_test(test, bin)
        results[sid] = { outcome = outcome, witness = witness }
      end
    end
  end
end

The run_test function is passed in as an argument, so a package can be useful to me only if it can run arbitrary functions in parallel. My goal is enough parallelism to get 100% CPU utilization on 6 to 8 cores.


Source: (StackOverflow)

Is LuaJIT really faster than every other JIT-ed dynamic languages? [closed]

According to the computer language benchmark game, the LuaJIT implementation seems to beat every other JIT-ed dynamic language (V8, Tracemonkey, PLT Scheme, Erlang HIPE) by an order of magnitude.

I know that these benchmarks are not representative (as they say: "Which programming language implementations have the fastest benchmark programs?"), but this is still really impressive.

In practice, is it really the case? Someone have tested that Lua implementation?


Source: (StackOverflow)

Alternatives to Lua as an embedded language?

I am working on an embedded system running Linux on a DSP. Now we want to make some parts of it scriptable and we are looking for a nice embeddable scripting language. These scripts should integrate nicely with our existing C++ code base, be small and fast.

I understand that Lua is the industry choice for problems like this. We will probably go with Lua because it is tried-and-true and proven to be stable and so on. However, as a programming language it has some rather quirky corners.

So, what alternatives are out there for embeddable languages?

EDIT:

This is about a year later.

We actually used Lua on our embedded system and it performs marvelously well. Over time, we added more and more scripting support to more and more parts of the project and that really helped to bring it along.

Performance is outstanding, really. Even rather complex operations that involve searching through long arrays or fancy string operations perform surprisingly well. We basically never ran into Lua related performance problems at all.

Interfacing with C functions is very straightforward and works really well. This allowed us to grow the scripting system painlessly.

Finally, we were astounded at how flexible Lua proved to be. Our Lua interpreter has to run on a system with a nonstandard memory allocator and without support for the double data type. There are two well-documented places in one header file we had to modify to make Lua work on that system. It is really well suited for embedding!


Source: (StackOverflow)

How to get number of entries in a Lua table?

Sounds like a "let me google it for you" question, but somehow I can't find an answer. The Lua # operator only counts entries with integer keys, and so does table.getn:

tbl = {}
tbl["test"] = 47
tbl[1] = 48
print(#tbl, table.getn(tbl))   -- prints "1     1"

count = 0
for _ in pairs(tbl) do count = count + 1 end
print(count)            -- prints "2"

How do I get the number of all entries without counting them?


Source: (StackOverflow)