I have been working with Lua lately and I have discovered that it is capable of doing some very interesting things. I have created a proof of concept that allows one Lua script to load another Lua script and use the loaded script to modify itself by passing itself as an argument to the creation function of the loaded script. The basic example here is from a simple card game.
In this specific example, I have a Card "object" which is really just a LuaTable. At the top of the Player.lua script I have:
local card = require "Card"
Then I create a card "object" by calling:
function Player:addSpecificCardToDeck(cardSuit, cardType, cardId)
table.insert(self.deck, card:new(cardSuit, cardType, cardId))
end
The Card.lua script loaded by require
contains code that loads another script during its creation. Here is the Card.lua script. Please ignore cardSuit in this example as that code is incomplete and I have omitted it.
Card.lua
Card = {} -- the table representing the class, which will double as the metatable for the instances
Card.__index = Card -- failed table lookups on the instances should fallback to the class table, to get methods
local cardList = require "Cardlist"
-- syntax equivalent to "MyClass.new = function..."
function Card:new(cardSuit, cardType, cardId)
local self = setmetatable({}, Card)
self.id = cardId
self.type = cardType
--this is where another script is loaded
print(self.id .. " cardID")
--getAbilityScriptsForId returns the appropriate string
self.testScript = require (cardList:getAbilityScriptsForId(2)) --2 is the proof of concept script being called
test = self.testScript:new(self)
test:increaseCardId()
print(self.id.. " new cardID") --the cardID will have increased by 1
return self
end
return Card
Here is the sample script being loaded:
SampleScript02.lua
SampleScript02 = {} -- the table representing the class, which will double as the metatable for the instances
SampleScript02.__index = SampleScript02 -- failed table lookups on the instances should fallback to the class table, to get methods
-- syntax equivalent to "MyClass.new = function..."
function SampleScript02:new(inputCard)
self.card = inputCard
return self
end
function SampleScript02:increaseCardId()
self.card.id = self.card.id + 1
end
return SampleScript02
As stated in the comments, the self.id of the script that loads the sample script will be incremented by 1. In theory, a script could pass itself into any potential script that modifies it. When a table is passed as the argument to a function in Lua, changes made to it inside that function apply to the original table. In contrast, when values such as integer or boolean are passed into a function, a copy is made instead.
What I am looking for is whether I am following the best practices for Lua, and also how to avoid any potential pitfalls that the language presents. Am I using require
properly? I am still learning the language, so any tips on syntax are also much appreciated.