Simple battery entity that uses datatables:
init.lua
AddCSLuaFile( "cl_init.lua" )
ENT.Type = "anim"
ENT.Base = "base_anim"
ENT.Spawnable = false
ENT.AdminSpawnable = false
function ENT:Initialize( )
self:SetModel( "models/items/car_battery01.mdl" )
self:PhysicsInit( SOLID_VPHYSICS )
self:SetMoveType( MOVETYPE_VPHYSICS )
self:SetSolid( SOLID_VPHYSICS )
local phys
phys = self:GetPhysicsObject( )
if ValidEntity( phys ) then
phys:Wake( )
--Prevent impact damage so we don't break / kill things
phys:AddGameFlag( FVPHYSICS_NO_IMPACT_DMG )
phys:AddGameFlag( FVPHYSICS_NO_NPC_IMPACT_DMG )
phys:AddGameFlag( FVPHYSICS_PENETRATING )
end
end
function ENT:SetupDataTables( )
self:DTVar( "Int", 0, "Power" )
end
function ENT:UpdatePower( i )
if i <= 0 then
self:SetColor( 100, 100, 100, 255 )
end
self.dt.Power = math.max( 0, i )
end
function ENT:TakePower( i )
self:UpdatePower( self.dt.Power - i )
end
function ENT:GetPower( )
return self.dt.Power
end
cl_init.lua
ENT.Type = "anim"
ENT.Base = "base_anim"
ENT.Spawnable = false
ENT.AdminSpawnable = false
ENT.CamPos = Vector( -4.8, -5.3, 2.5 )
ENT.CamAngle = Angle( 0, 90, -90 )
ENT.CamScale = .05
ENT.Width = 212
ENT.Height = 16
ENT.BatteryPower = 1024
function ENT:SetupDataTables( )
self:DTVar( "Int", 0, "Power" )
end
function ENT:DrawDisplay( )
local r, g, b
self.CurrentPower = math.Approach( self.CurrentPower or 0, self.TargetPower, FrameTime( ) * 2048 )
f = math.Clamp( self.CurrentPower / self.BatteryPower, 0, 1 )
surface.SetDrawColor( 000, 000, 000, 255 )
surface.DrawRect( 0, 0, self.Width, self.Height )
surface.SetDrawColor( ( 1 - f ) * 189, 189 * f, 0, 150 )
surface.DrawRect( 0, 0, self.Width * f, self.Height )
end
function ENT:Draw( )
local ok, err, pos, ang
self:DrawModel( )
pos = self:GetPos( ) + self:GetForward( ) * self.CamPos.x + self:GetRight( ) * self.CamPos.y + self:GetUp( ) * self.CamPos.z
ang = self:GetAngles( )
ang:RotateAroundAxis( ang:Right( ) , self.CamAngle.y )
ang:RotateAroundAxis( ang:Up( ) , self.CamAngle.r )
ang:RotateAroundAxis( ang:Forward( ) , self.CamAngle.p )
self.TargetPower = self.dt.Power or 0
cam.Start3D2D( pos, ang, self.CamScale )
--Don't need to
ok, err = pcall( self.DrawDisplay, self )
if not ok then
ErrorNoHalt( err .. "
" )
end
cam.End3D2D( )
end
Each entity has a grand total of 24 different data variables it can have ( four int, float, bool, vector, ehandle, and angle ), which can lead to conflicts between different addons ( eg, I have an addon that uses two dt ints on npcs, but I use 2 and 3 to hopefully improve compatability as most people will start at 0 ).
As hinting above, the indices for the values range from 0 to 3, and the example code uses the literal table method, which isn’t really needed.
If you don’t want to use that, you can do this:
someent:SetDTInt( 3, 24 )
And then somewhere else, anywhere:
someint = someent:GetDTInt( 3 )