lua-users home
lua-l archive

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


Hello, 

That's nice
I made somthing like you, but with mine you can pass functions too, its called LuaBash[1]
Here is the example i made:
The bash file

#!/bin/bash

# init lua bash and load code chunk from file internal.lua.
enable -f ./build/luabash.so luabash
luabash load ./internal.lua

# perform some arithmetic using a lua function called "plus".
total=0
for ((i=1;i<3;i++)) ; do
  for ((j=1;j<3;j++)) ; do
    plus $i $j
  done
done
echo "total sum is: " $total


# bash function to be called from within lua context
some_bashy_function ()
{
  if [ -n "$2" ] ; then
  shift
  some_bashy_function $@
  echo "$1"
  fi
}

# call the lua function that calls bash function above
callbash

# test if io redirection works
cat <<EOF | redirections | sed 's,xx,yy,g'
line one
line two
line three
EOF

# print ten shell variables
printenv | head -n 10

one
echo $?

zero
echo $?

str
echo $?

boolean
echo $?

-- And here is the lua file.

function plus(a,b)
   total=bash.getVariable("total")
   if total == nil then total=0 end
   prod=a*b
   total=total+prod
   print(a.." * "..b.." = "..prod)
   bash.setVariable("total", total)
   return result
end

function callbash()
   goodresult=bash.call("some_bashy_function", "trash", "test", "a", "is", "this")
   badresult=bash.call("this-command-is-intentionally-wrong")
   print ("returncodes were: "..goodresult .. " " .. badresult)
end

function redirections()
   repeat
      a=io.read()
      if a~=nil then print("xx"..a.."xx") end
   until a==nil
end

function printenv()
   env=bash.getEnvironment()
   for key,val in pairs(env) do
      print(key.."="..val)
   end
end

function zero()
   return 0
end

function one()
   return 1
end

function str()
   return "abc"
end

function two()
   return 1, "two" -- :-)
end

function boolean()
   return true
end

-- register shortcuts to functions above
bash.register("plus")
bash.register("callbash")
bash.register("redirections")
bash.register("printenv")
bash.register("zero")
bash.register("one")
bash.register("str")
bash.register("two")
bash.register("boolean")


The cool part is that you can also use it on the interactive shell (i wich is what i use it for)
It needs some cleaning and documentation, wich i will do if there is interest.

[1] https://github.com/masterkorp/LuaBash