Home > Back-end >  Problem with Load function in Lua while execution
Problem with Load function in Lua while execution

Time:03-06

print("i", "j", "i & j")
for i = 0,1 do
   for j=0,1 do
   print(i, j, i & j)
   end
end

The above code works fine in Lua. It gives the following output.

i   j   i & j
0   0   0
0   1   0
1   0   0
1   1   1

However the following code doesn't work. Basically I want to generate Truth Table based on some user input. There seems to be issue with load function. Probably it is related with type of variable that function load handles. Can anyone suggest? Can we write Lua function to achieve same? Here is the code that doesn't work.

str="i & j"
print("i", "j", "i & j")
for i = 0,1 do
for j=0,1 do
   print(i,j,load(str))
end
end

CodePudding user response:

Here's an attempt which is supposed to work with a maximum of nearly sixty values:

-- Lua >= 5.3
local concat = table.concat

local str    = "((i | j) ~ k) & l" -- io.read() ?
local sep    = " "

local values = {} -- 0 or 1
-- i, j, k, etc.
local names  = setmetatable({},
  {__index = function(t,k)
    t[k] = 0
    values[#values 1] = k
    return 0
  end}
)

local aux = {} -- Values to be printed
load("return " .. str,nil,"t",names)()  -- Initialization
local n = #values
print(concat(values,sep) .. sep .. str) -- Variables
for i = 0,(1<<n)-1 do -- 2^n evaluations
  local k = i
  for j = n,1,-1 do
    names[values[j]] = k % 2
    aux[j] = k % 2
    k = k >> 1
  end
  print(concat(aux,sep) .. sep .. load("return " .. str,nil,"t",names)())
end
i j k l ((i | j) ~ k) & l
0 0 0 0 0
0 0 0 1 0
0 0 1 0 0
0 0 1 1 1
0 1 0 0 0
0 1 0 1 1
0 1 1 0 0
0 1 1 1 0
1 0 0 0 0
1 0 0 1 1
1 0 1 0 0
1 0 1 1 0
1 1 0 0 0
1 1 0 1 1
1 1 1 0 0
1 1 1 1 0

CodePudding user response:

use little tricks:

local str="return i * j" -- or i & j for v5.3 lua
print("i", "j", "i & j")
for i = 0,1 do
    for j=0,1 do
       local  s = str:gsub("i",i):gsub("j",j)
       print(i,j, loadstring(s)() )
    end
end
  • Related