3

I am working on a scripting layer for my game engine. Currently I am using a Script as a Class, adding a method to the "Table" named new. This function basically created an instantiated copy of the Class. I call this function from the C API when an instance of the script is needed.

function PlayerController:new(o)
    print('A new instance of the PlayerController has been created');

    o = o or {}
    setmetatable(o, self)
    self.__index = self
    return o
end

My question is: How can I take the above Lua code, and move that into C so it is not required to be added to every script file I write for this system?

hjpotter92
  • 78,589
  • 36
  • 144
  • 183
Don Duvall
  • 839
  • 6
  • 10
  • Bad idea. Why can't you just use a lua script (which might call others) to initialize your lua state and put any functions the host provides into proper Lua classes? That is far easier to write, easier to maintain and easier to extend. Should not hurt performance either. – Deduplicator Jun 16 '14 at 21:10
  • Also, consider using the call meta-method for defining classes and for instantiating them. – Deduplicator Jun 16 '14 at 21:12
  • I am not sure I follow. Also why is it a bad idea to add a 'new' method to each of my scripts programmatically? Just curious. Also, I am looking into meta-method. – Don Duvall Jun 16 '14 at 22:24
  • Bad idea, because that's far easier done in Lua. A good framework (10 minutes to roll your own basic one, naturally in Lua itself) should mostly remove the need for the `new`-function. – Deduplicator Jun 16 '14 at 22:32
  • Do you have any links to a good article on this topic? Or what I might search for in google? I am having difficulty finding any good resources on this. Thanks, – Don Duvall Jun 16 '14 at 22:45
  • 1
    I suggest you use one of the many Lua OOP frameworks out there, such as LOOP. – Colonel Thirty Two Jun 16 '14 at 23:43

1 Answers1

0

You might want to create a class declaration function to do this for you. Here is a complete "helper.lua" file:

local lib = {type = 'helper'}
local CALL_TO_NEW = {__call = function(lib, ...) return lib.new(...) end}

function lib.class(class_name, tbl)
  local lib = tbl or {}
  lib.type = class_name
  lib.__index = lib

  -- Default "new" method
  function lib.new()
    return setmetatable({}, lib)
  end

  -- Enable foo.Bar() instead of foo.Bar.new()
  return setmetatable(lib, CALL_TO_NEW)
end
return lib

Usage example:

local helper = require 'helper'
local lib = helper.class 'foo.Bar'

-- optional new function if there needs to be some argument handling
function lib.new(args)
  local self = {}
  -- ...
  return setmetatable(self, lib)
end

return lib

lub.class

This is a real world minimal class declaration and setup system. It is used in many luarocks such as xml, yaml, dub, etc:

Anna B
  • 5,997
  • 5
  • 40
  • 52