z_mirror/CursorEnhancements
git clone https://git.raiguard.me/z_mirror/CursorEnhancements
55b779d
trunk
1local util =require ( "scripts.util" ) 2 3local max_history_size =10 4 5--- @param e EventData.CustomInputEvent 6local function on_recall_last_item ( e ) 7local player =game . get_player ( e . player_index ) 8if not player then 9return 10end 11 12local history =storage . item_history [ e . player_index ] 13if not history then 14return 15end 16local index =storage . history_index [ e . player_index ] 17 18if not ( history and index ) then 19return 20end 21 22local cursor_item =util . get_cursor_item ( player ) 23if cursor_item and index <= 1 then 24index =index + 1 25end 26 27local item =history [ index ] 28if not item or not item . name . valid or not item . quality . valid then 29return 30end 31 32util . set_cursor ( player , item ) 33 34if index + 1 > # history then 35storage . history_index [ e . player_index ] =0 36else 37storage . history_index [ e . player_index ] =index + 1 38end 39 40storage . item_update_tick [ e . player_index ] =e . tick 41end 42 43--- @param e EventData.on_player_cursor_stack_changed 44local function on_player_cursor_stack_changed ( e ) 45local player =game . get_player ( e . player_index ) 46if not player then 47return 48end 49 50if e . tick == storage . item_update_tick [ e . player_index ] then 51return 52end 53 54local history =storage . item_history [ e . player_index ] 55if not history then 56history ={} 57storage . item_history [ e . player_index ] =history 58end 59 60storage . history_index [ e . player_index ] =1 61 62local cursor_item =util . get_cursor_item ( player ) 63if not cursor_item or cursor_item . name . has_flag ( "spawnable" ) then 64return 65end 66 67for i , history_item in pairs ( history ) do 68if serpent . line ( cursor_item ) == serpent . line ( history_item ) then 69table . insert ( history , 1 , table . remove ( history , i )) 70return 71end 72end 73 74table . insert ( history , 1 , cursor_item ) 75 76if # history > max_history_size then 77table . remove ( history ) 78end 79end 80 81local function init () 82--- @type table<uint, ItemWithQualityID[]?> 83storage . item_history ={} 84--- @type table<uint, number> 85storage . item_update_tick ={} 86--- @type table<uint, number> 87storage . history_index ={} 88end 89 90--- @type event_handler 91local recall_last_item ={} 92 93recall_last_item . on_init =init 94recall_last_item . on_configuration_changed =init 95 96recall_last_item . events ={ 97[ "cen-recall-last-item" ] =on_recall_last_item , 98[ defines . events . on_player_cursor_stack_changed ] =on_player_cursor_stack_changed , 99} 100 101return recall_last_item