-- lua/modules/resource_management.lua
if SERVER then
util.AddNetworkString("Industrialization_UpdateInventory")
util.AddNetworkString("Industrialization_Notify")
PlayerInventory = PlayerInventory or {}
AvailableResources = AvailableResources or {
wood = 500,
metal = 300,
oil = 200,
minerals = 100,
}
-- Initialize player inventory on spawn
hook.Add("PlayerInitialSpawn", "Industrialization_InitInventory", function(player)
PlayerInventory[player:SteamID()] = {
wood = 0,
metal = 0,
oil = 0,
minerals = 0,
refined_metal = 0,
electronics = 0,
-- Initialize other resources
}
end)
-- Function to add resources to player inventory
function AddPlayerResource(player, resource, qty)
if not PlayerInventory[player:SteamID()] then return false end
if not ResourceTypes[resource] then return false end
if (PlayerInventory[player:SteamID()][resource] or 0) + qty <= 1000 then -- Max limit
PlayerInventory[player:SteamID()][resource] = PlayerInventory[player:SteamID()][resource] + qty
AvailableResources[resource] = (AvailableResources[resource] or 0) - qty
-- Notify player
player:ChatPrint("You have gained " .. qty .. " " .. ResourceTypes[resource].name)
-- Update UI
net.Start("Industrialization_UpdateInventory")
net.WriteTable(PlayerInventory[player:SteamID()])
net.Send(player)
return true
else
player:ChatPrint("Cannot carry more " .. ResourceTypes[resource].name)
return false
end
end
-- Function to remove resources from player inventory
function RemovePlayerResource(player, resource, qty)
if not PlayerInventory[player:SteamID()] then return false end
if not ResourceTypes[resource] then return false end
if PlayerInventory[player:SteamID()][resource] and PlayerInventory[player:SteamID()][resource] >= qty then
PlayerInventory[player:SteamID()][resource] = PlayerInventory[player:SteamID()][resource] - qty
AvailableResources[resource] = (AvailableResources[resource] or 0) + qty
-- Notify player
player:ChatPrint("You have used " .. qty .. " " .. ResourceTypes[resource].name)
-- Update UI
net.Start("Industrialization_UpdateInventory")
net.WriteTable(PlayerInventory[player:SteamID()])
net.Send(player)
return true
else
player:ChatPrint("Not enough " .. ResourceTypes[resource].name)
return false
end
end
-- Function to spawn initial resource nodes
function SpawnInitialResourceNodes()
local positions = {
Vector(100, 100, 10),
Vector(200, 200, 10),
Vector(300, 300, 10),
-- Add more positions as needed
}
for _, pos in ipairs(positions) do
local resourceType = table.Random({"wood", "metal", "oil", "minerals"})
SpawnResourceNode(resourceType, pos)
end
end
-- Function to spawn a resource node
function SpawnResourceNode(resourceType, position)
if not ResourceTypes[resourceType] then return end
local node = ents.Create("resource_node")
node:SetModel(ResourceTypes[resourceType].model)
node:SetPos(position)
node:SetNWString("ResourceType", resourceType)
node:SetNWInt("ResourceQuantity", 10) -- Initial quantity
node:Spawn()
end
-- Recycling system
function RecycleWaste(player, wasteType, qty)
if ResourceTypes[wasteType] and wasteType == "scrap_metal" then
if RemovePlayerResource(player, "scrap_metal", qty) then
AddPlayerResource(player, "refined_metal", qty)
player:ChatPrint("Recycled " .. qty .. " Scrap Metal into Refined Metal")
end
else
player:ChatPrint("Invalid waste type for recycling.")
end
end
-- Handle player commands or interactions
-- Example: Using a recycling facility
concommand.Add("industrial_recycle", function(player, cmd, args)
local wasteType = args[1]
local qty = tonumber(args[2]) or 1
RecycleWaste(player, wasteType, qty)
end)
end
The error you're encountering:
code
addons/gmod-industrialization/lua/modules/resource_management.lua:30: attempt to index local 'player' (a nil value)
indicates that the player variable is nil when the AddPlayerResource function is being called. This error occurs because the function is trying to access properties of a nil value, specifically player:SteamID().
To resolve this issue, let's walk through the steps to identify and fix the problem.
This indicates that AddPlayerResource is being called from resource_node/init.lua at line 46, and it's being called multiple times (9 times in this case).
Identifying the Problem
Function Definition:
lua
function AddPlayerResource(player, resource, qty)
if not PlayerInventory[player:SteamID()] then return false end
-- Further processing...
end
The function expects a valid player object to be passed. If player is nil, player:SteamID() will throw an error because you're trying to call a method on a nil value.
Potential Call Sites:
Since the error points to resource_node/init.lua:46, the issue likely originates from how AddPlayerResource is being called within that file.
Without the code from resource_node/init.lua, we can infer that AddPlayerResource might be called during the entity's initialization or some other event where a valid player object isn't available.
Steps to Fix the Issue
1. Inspect resource_node/init.lua
Locate the resource_node/init.lua file and navigate to line 46. Examine how AddPlayerResource is being called. Ensure that a valid player object is being passed as the first argument.
Common Mistakes:
Calling AddPlayerResource during the entity's initialization (Initialize function) without a player context.
Passing an incorrectly obtained player object or forgetting to pass it altogether.
Example of a Potential Issue:
lua
-- resource_node/init.lua
function ENT:Initialize()
-- Incorrect: No player context available here
AddPlayerResource(nil, "wood", 10)
end
2. Correct the Call to AddPlayerResource
Ensure that AddPlayerResource is called in response to a player action where a valid player object is available. For example, when a player interacts with a resource node to harvest resources.
Example Correction:
lua
-- resource_node/init.lua
function ENT:Use(activator, caller)
if IsValid(caller) and caller:IsPlayer() then
AddPlayerResource(caller, "wood", 10)
-- Additional logic...
else
print("AddPlayerResource called with invalid player")
end
end
Key Points:
Validation: Before calling AddPlayerResource, check if the caller is a valid player.
Context: Ensure that the function is called within an event or hook where a player is interacting with the resource node.
3. Add Defensive Programming in AddPlayerResource
Even with corrections, it's good practice to make your functions robust by handling unexpected inputs gracefully.
Updated AddPlayerResource:
lua
function AddPlayerResource(player, resource, qty)
if not IsValid(player) or not player:IsPlayer() then
print("AddPlayerResource called with invalid player:", player)
return false
end
local steamID = player:SteamID()
if not PlayerInventory[steamID] then
print("PlayerInventory not initialized for SteamID:", steamID)
return false
end
if not ResourceTypes[resource] then
print("Invalid resource type:", resource)
return false
end
if (PlayerInventory[steamID][resource] or 0) + qty <= 1000 then -- Max limit
PlayerInventory[steamID][resource] = (PlayerInventory[steamID][resource] or 0) + qty
AvailableResources[resource] = (AvailableResources[resource] or 0) - qty
-- Notify player
player:ChatPrint("You have gained " .. qty .. " " .. ResourceTypes[resource].name)
-- Update UI
net.Start("Industrialization_UpdateInventory")
net.WriteTable(PlayerInventory[steamID])
net.Send(player)
return true
else
player:ChatPrint("Cannot carry more " .. ResourceTypes[resource].name)
return false
end
end
Benefits:
Validation: Checks if player is valid and is indeed a player.
Logging: Prints informative messages to the server console for easier debugging.
Robustness: Prevents the function from proceeding with invalid data, avoiding runtime errors.
4. Ensure Proper Initialization of PlayerInventory
In your PlayerInitialSpawn hook, you initialize PlayerInventory for a player. Ensure this hook is functioning correctly and that PlayerInventory is properly set up before any resource management functions are called.
Example:
lua
hook.Add("PlayerInitialSpawn", "Industrialization_InitInventory", function(player)
PlayerInventory[player:SteamID()] = {
wood = 0,
metal = 0,
oil = 0,
minerals = 0,
refined_metal = 0,
electronics = 0,
-- Initialize other resources
}
-- Optionally notify the player
player:ChatPrint("Welcome to Industrialization! Your inventory has been initialized.")
end)
Considerations:
Timing: Ensure that players are fully spawned and initialized before they can interact with resource nodes.
Persistence: If you intend for PlayerInventory to persist across sessions, consider saving and loading it appropriately.
Summary
The error arises because the AddPlayerResource function is being called with a nil value for the player parameter. To fix this:
Check Call Sites: Inspect resource_node/init.lua at line 46 and ensure a valid player object is being passed.
Validate Player Objects: Before calling AddPlayerResource, ensure the player is valid and exists.
Defensive Coding: Enhance AddPlayerResource with additional checks to handle nil or invalid players gracefully.
Ensure Proper Initialization: Confirm that PlayerInventory is correctly initialized for each player during their initial spawn.
By following these steps, you should be able to eliminate the nil player error and ensure that your resource management system functions smoothly.
If you continue to experience issues or need further assistance, please provide the relevant section of resource_node/init.lua, especially around line 46, so I can offer more targeted help.