How to put an item from player's main inventory into their cursor?

Place to get help with not working mods / modding interface.
Post Reply
jarcionek
Fast Inserter
Fast Inserter
Posts: 137
Joined: Thu Mar 10, 2016 11:26 am
Contact:

How to put an item from player's main inventory into their cursor?

Post by jarcionek »

I want to auto-equip an item when user presses a key and also spawn the item if they don't have it in inventory.

I have noticed that the following code, puts the item in hand correctly, but it doesn't reserve a slot for it in the main inventory - so if logistic robots fill player's inventory with junk, the player will not be able to put that item back:

Code: Select all

player.get_main_inventory().main_inventory.find_item_stack("ZoomingReinvented_binoculars")
player.clean_cursor()
player.cursor_stack.swap_stack(binoculars_in_inventory)
I though that this problem was resolved by making a main inventory the only inventory, while all other things (like cursor or tool belt) are just shortcuts/links. However it feels like cursor was a separate inventory, while the hand icon showing in the main inventory to reserve a slot was just some hack...

Overall, a task that I would expect to be a few lines of code, has already a dozen and still doesn't work the way I would like it to:

Code: Select all

if not player.cursor_stack.valid_for_read or player.cursor_stack.name ~= "ZoomingReinvented_binoculars" then
    local main_inventory = player.get_main_inventory();
    local binoculars_in_inventory = main_inventory.find_item_stack("ZoomingReinvented_binoculars")
    if not binoculars_in_inventory and main_inventory.can_insert("ZoomingReinvented_binoculars") then
        main_inventory.insert("ZoomingReinvented_binoculars")
    end
    binoculars_in_inventory = main_inventory.find_item_stack("ZoomingReinvented_binoculars")
    if binoculars_in_inventory then
        player.clean_cursor()
        player.cursor_stack.swap_stack(binoculars_in_inventory)
    end
end
Is there any way to achieve this? If there is, is there any way to achieve this in an easier way?

Post Reply

Return to “Modding help”