-------------------------------------------------------------------------------- -- Title: LWTemplate.lua -- Description: Like a square peg in a round hole -- Author: Raphaël Szwarc http://alt.textdrive.com/lua/ -- Creation Date: February 1, 2005 -- Legal: Copyright (C) 2005 Raphaël Szwarc -------------------------------------------------------------------------------- -- import dependencies local LUObject = require( "LUObject" ) local LULog = require( "LULog" ) local table = require( "table" ) -- define the class local super = LUObject local self = super() -- initialization method function self:init( aContent ) self = super.init( self ) self._content = aContent return self end -- method to access this template content function self:content() return self._content end -- method to copy this template function self:copy() return self:new( self:content() ) end -- method to access this template templates function self:templates() if self._templates == nil then self._templates = {} end return self._templates end -- method to access a specific template function self:get( aKey ) local someTemplates = self:templates() local aTemplate = someTemplates[ aKey ] if aTemplate == nil then local aContent = self:content() local anOpenStart, anOpenEnd = aContent:find( "(t:" .. aKey .. ")", 1, true ) local aCloseStart, aCloseEnd = aContent:find( "(/t:" .. aKey .. ")", anOpenEnd, true ) aTemplate = self:new( aContent:sub( anOpenEnd + 1, aCloseStart - 1 ) ) someTemplates[ aKey ] = aTemplate self._content = aContent:sub( 1, anOpenStart - 1 ) .. "(v:" .. aKey .. ")" .. aContent:sub( aCloseEnd + 1 ) end return aTemplate:copy() end -- method to set a variable value function self:put( aKey, aValue ) local someVariables = self:variables() local aBuffer = someVariables[ aKey ] if aBuffer == nil then aBuffer = {} someVariables[ aKey ] = aBuffer end aBuffer[ #aBuffer + 1 ] = tostring( aValue or "" ) return self end -- method to access this template variables function self:variables() if self._variables == nil then self._variables = {} end return self._variables end -- method for string representation function self:toString() local aContent = self:content() local aTable = {} for aKey, aBuffer in pairs( self:variables() ) do aKey = ( "(v:%s)" ):format( aKey ) aTable[ aKey ] = table.concat( aBuffer, "" ) end aContent = aContent:gsub( "(%(v%:%w-%))", aTable ) return aContent end return self