1   Introduction

In a previous post I discussed how to use the API generated by generateDS to access and manipulate objects in the object tree produced by generateDS from and XML instance document. See: http://davekuhlman.org/gds-api-guidance.html.

In this article we'll see how to use Lupa, which is Lua embedded in Python, to do similar tasks.

More information:

2   The sample code

The sample code is here -- plants_lua.zip.

  • The Python module -- plants_update03.py -- This module (1) uses a module generated by generateDS to parse and XML instance document, then (2) uses Lupa to call functions in the Lua module.
  • The Lua module -- testlupa01.lua -- This is required from within the Python code. The Lua functions in it are called from the Python module using Lupa.

Things to notice in the Python module (see code after comment "Begin Lua tests"):

  • Having imported Lupa, we create an instance of the Lua runtime.
  • Next we require the Lua module, which loads our Lua module into our Lua runtime. This gives us access to the Lua functions in that module from Python.
  • After that, we can access and manipulate the object tree (rooted at plantCollection from either Python or Lua. Our calls to the functions in our Lua module use the loaded module in luamodule.
  • We use plantCollection.export(sys.stdout, 0) to display the object tree as XML so that we can see our changes.

Things to notice in the Lua module (testlupa01.lua):

  • We use a conventional Lua organization for a module: (1) create a table; (2) scope objects to be exported in that table; and (3) return the table at the end of the module. See: http://lua-users.org/wiki/ModuleDefinition.

  • Much of the code is quite analogous to the equivalent code in Python, but with Lua syntax. For example:

    • We can access classes in the generated Python module and create instances of them. Example:

      local veg = gdslib.vegetableType()
      
    • We can access and set attributes in the (Python) classes. Example:

      local objs = root.vegetables.vegetable
      
  • We use the python.enumerate function to simplify enumeration over a collection. See: https://pypi.org/project/lupa/#iteration-in-lua.

    local objs = root.vegetables.vegetable
    for _, obj in python.enumerate(objs) do
      obj.name = string.upper(obj.name)
    end
    
  • We can export the tree in Lua, but we need to use a Python file (for example, sys.stdout), and not a Lua file (for example, not io.stdout). So, for example, if we have passed sys.stdout from Python to Lua, then in Lua, we can do:

    function M.export_it(root, stdout)
      root.export(stdout, 3)
    end
    

Published

Category

python

Tags

Contact